Ruby on rails 如何与长时间运行的进程并行地从Rails ActionController返回响应?

Ruby on rails 如何与长时间运行的进程并行地从Rails ActionController返回响应?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我主要将Node用于后端服务,但使用Ruby 1.9.3维护Rails 3.2 API。最近,我们意识到在某些情况下,我们的FoosController#createcontroller方法花费的时间太长,以至于客户端在收到响应之前超时。我有点像 def create if check_for_bad(params) # Validation step return bad_params_error # Return 400 error end Foo.create(par

我主要将Node用于后端服务,但使用Ruby 1.9.3维护Rails 3.2 API。最近,我们意识到在某些情况下,我们的
FoosController#create
controller方法花费的时间太长,以至于客户端在收到响应之前超时。我有点像

def create
  if check_for_bad(params) # Validation step
    return bad_params_error # Return 400 error
  end

  Foo.create(params) # Need to move this to a parallel thread

  output = { status: 200, message: 'OK' }
  return render json:output
end
在初始参数检查之后,客户端不需要知道任何错误,因此我希望在运行
Foo\create
之前返回响应,但我确实需要将
params
传递给该方法。我曾尝试将其放入
after\u filter
方法中(在尝试
after\u action
时,我得到了
未定义的方法

看起来这应该很容易,可能是使用光纤或在其上构建的宝石,但我对可用的东西不太熟悉,无法确保我所做的事情不会造成比我所解决的问题更多的问题


提前感谢您的帮助。

正如@Broisasse所提到的,我建议您在Sidekiq的后台进行此操作。Sidekiq上的指南给出了整体设置,但在这种情况下,您必须改变一下您对创建Foo意味着什么的想法

您将立即创建一个状态为“挂起”的Foo,然后将您的参数和创建的Foo id传递给后台工作人员,这将是一项艰巨的工作。如果在那里一切都成功,您将更新您的Foo,使其“完成”或“准备就绪”

要执行Foo创建后台工作,您需要创建一个worker:

# app/workers/CreateFooWorker.rb
class CreateFooWorker
  include Sidekiq::Worker

  def perform(foo_id, params)
    if foo = Foo.find(foo_id) && foo.update_attributes(params)
      foo.update_attribute(:state, "ready")
    end
  end
end

# Change create to immediately create a foo without the params
# and then actually build the real foo with params in the background
def create
  if check_for_bad(params) # Validation step
    return bad_params_error # Return 400 error
  end

  foo = Foo.create(state: "pending") # Just create with a pending state...
  CreateFooWorker.perform_async(foo.id, params) # Now do the real work in the background

  # You're going to want to retun the foo json here
  # because your client will need to hold onto the
  # foo.id and query the server for when the foo is "ready"
  return render json: foo.to_json, status: created
end
看看sidekiq`:谢谢@BroiSatse——sidekiq成功了。如果你想回答更详细的问题,我会同意的。否则,我会写下明天的效果,以防其他人有类似的问题。