这个异步Rails操作安全吗?



我试图使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

下面是一个如何执行异步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

最新更新