这个异步Rails操作安全吗?

时间:2014-07-27 13:58:33

标签: ruby-on-rails thread-safety thin

我试图使rails操作异步且无阻塞。我使用的是rails 3.2和瘦Web服务器。以下代码是否安全?

class AnalyticsController < ApplicationController
  # [...]

  # called by an XHR request, displaying a spinner in the main page while loading
  def load
    Thread.new do
      @answer = Analytic.build_stuff_with_blocking_io # can take up to 60sec
      request.env['async.callback'].call [200, {}, render_to_string(partial: '/analytics/dashboard', layout: false)]
    end
    throw :async
  end

end

1 个答案:

答案 0 :(得分:1)

以下是如何执行异步Rails操作的示例:

class ApplicationController < ActionController::Base
  def async
    EM.defer do
      sleep 5 # Some work that take a long time.
      request.env['async.callback'].call response
    end

    throw :async
  end
end

确保您的环境中有config.allow_concurrency = true。并且您正在使用能够进行异步响应的服务器,例如Thin。

如果您使用的是Thin:

bundle exec thin --threaded start