Rails 6从Sidekiq Job抓取结果-这是可能的吗?



我有Sidekiq工作(SyncProductsWorker),它触发一个类Imports::SynchronizeProducts负责一些外部API调用。

module Imports
class SyncProductsWorker
include Sidekiq::Worker
sidekiq_options queue: 'imports_sync'
def perform(list)
::Imports::SynchronizeProducts.new(list).call
end
end
end

Imports::SynchronizeProducts类给出了一个单子结果数组和一些注释,例如

=> [Failure("999999 Product code is not valid"), Failure(" 8888889 Product code is not valid")]

我想捕获这些结果以在FE上显示它们。这可能吗?如果我这样做:

def perform(list)
response = ::Imports::SynchronizeProducts.new(list).call
response
end

然后在控制器内部:

def create
response = ::Imports::SyncProductsWorker.perform_async(params[:product_codes])
render json: { result: response, head: :ok }
end

我将得到一些数字作为结果

=> "df3615e8efc56f8a062ba1c2"

我不相信你想要的是可能的

https://github.com/mperham/sidekiq/issues/3532

返回值将像Ruby进程中任何其他未使用的数据一样被GC。工作没有"结果"。在Sidekiq中,Sidekiq对值不做任何处理。

你需要某种模型来跟踪你的后台任务。这是即兴发挥,但应该给你一个想法。

# @attr result [Array]
# @attr status [String] Values of 'Pending', 'Error', 'Complete', etc..
class BackgroundTask < ActiveRecord
attr_accessor :product_codes
after_create :enqueue

def enqueue
::Imports::SyncProductsWorker.perform_async(product_codes, self.id)
end
end
def perform(list, id)
response = ::Imports::SynchronizeProducts.new(list).call
if (response.has_errors?)
BackgroundTask.find(id).update(status: 'Error', result: response)
else
BackgroundTask.find(id).update(status: 'Complete', result: response)
end
end

然后使用BackgroundTask模型作为你的前端显示。

最新更新