Rails 4,Live Streaming,保持打开状态,阻止请求

我正在尝试使用Rails 4 Live Streaming组件。 这一切都有效,除了看起来流保持打开并阻止新的请求。

关闭或单击应用程序中的新链接时,如何确保连接正常关闭?

这是我的直播活动控制器。

def events response.headers["Content-Type"] = "text/event-stream" redis = Redis.new redis.psubscribe("participants.*") do |on| on.pmessage do |pattern, event, data| response.stream.write("event: #{event}\n") response.stream.write("data: #{data}\n\n") end end rescue IOError ensure redis.quit response.stream.close end 

数据库conf

 production: adapter: postgresql encoding: unicode database: ************ pool: 1000 username: ************ password: ************ timeout: 5000 

我在使用postgresql 9.2.x的Ubuntu 10.04上使用puma作为独立的webserver(我没有需要由nginx提供的大量静态文件)。

您必须更改开发环境设置才能启用此function。

在config / environments / development.rb中添加或更改它:

 config.cache_classes = true config.eager_load = true 

请参阅http://railscasts.com/episodes/401-actioncontroller-live?view=asciicast

Puma不应该阻塞,应该允许多个线程允许多个请求。

向您介绍代码中发生的事情。 您目前在每个请求中使用此代码中的两个线程。 请求进入的线程,以及用于保持打开连接的后台线程。

由于操作方法结束时的确保阻止,您的连接将正确关闭。

 def events response.headers["Content-Type"] = "text/event-stream" redis = Redis.new # blocks the current thread redis.psubscribe("participants.*") do |on| on.pmessage do |pattern, event, data| response.stream.write("event: #{event}\n") response.stream.write("data: #{data}\n\n") end end # stream is on a background thread and will remain open until # redis.psubscrie exits. (IO Error, etc) rescue IOError ensure redis.quit response.stream.close end 

您还可以调查另一个名为rainbows的服务器( http://rainbows.rubyforge.org/index.html ),这是另一个非常好的机架服务器,用于打开请求。

这里还有一个与流线程相关的线程挂起https://github.com/rails/rails/issues/10989

Interesting Posts