gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:00:35 25 4
gpt4 key购买 nike

我有数据流通过 http 命中传给我。我想实时更新数据。我已经开始将 HTTP 命中数据推送到 redis pubsub。现在我想把它展示给用户。

我想在 redis channel 上获得一些数据后立即更新用户的屏幕。我想使用 ruby​​,因为这是我熟悉的语言。

最佳答案

我会在客户端使用 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

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

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

关于ruby - 在ruby中使用redis pubsub实时显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com