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

时间:2013-08-05 09:58:22

标签: ruby-on-rails ruby-on-rails-4 http-live-streaming puma

我正在尝试使用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提供的大量静态文件)。

2 个答案:

答案 0 :(得分:8)

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

在config / environments / development.rb中添加或更改此内容:

config.cache_classes = true
config.eager_load = true

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

答案 1 :(得分:2)

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

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

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