在ruby中使用redis pubsub进行实时显示?

piy*_*ush 3 ruby publish-subscribe redis

我有一个数据流通过http命中来找我.我想实时更新数据.我已经开始将HTTP命中数据推送到redis pubsub.现在我想向用户展示它.

我想在redis频道上获得一些数据后立即更新用户的屏幕.我想使用红宝石,因为这是我熟悉的语言.

bio*_*net 7

我会在客户端使用Sinatra的"流"功能和EventSource.但是,IE离开了.

以下是从https://github.com/redis/redis-rb/blob/master/examples/pubsub.rb中提取的一些主要功能服务器端代码(另一个选项是https://github.com/pietern/hiredis-rb) :

get '/the_stream', provides: 'text/event-stream' do
  stream :keep_open do |out|
    redis = Redis.new
    redis.subscribe(:channel1, :channel2) do |on|
      on.message do |channel, msg|
        out << "data: #{msg}\n\n" # This is an EventSource message
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

客户端.大多数现代浏览器都支持EventSource,IE除外:

var stream = new EventSource('/the_stream');
stream.onmessage = function(e) {
  alert("I just got this from the server: " + e.data);
}
Run Code Online (Sandbox Code Playgroud)