【问题标题】:How to return response from Rails ActionController in parallel with long-running process?如何从 Rails ActionController 与长时间运行的进程并行返回响应?
【发布时间】:2014-06-06 13:43:47
【问题描述】:

我主要将 Node 用于后端服务,但使用 Ruby 1.9.3 维护 Rails 3.2 API。最近我们意识到,在某些极端情况下,我们的FoosController#create 控制器方法花费了很长时间,以至于客户端在收到响应之前就超时了。我有类似的东西

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_filter 方法中(我在尝试after_action 时得到undefined method)。

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

提前感谢您的帮助。

【问题讨论】:

  • 看看sidekiq`:github.com/mperham/sidekiq
  • 感谢@BroiSatse -- Sidekiq 成功了。如果您想更详细地回答,我会批准。否则我会在明天写出可行的方法,以防其他人遇到类似问题。

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

正如@BroiSatse 提到的,我建议在后台使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2012-12-14
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多