我正在尝试将文件下载分解为后台进程。 我的资产存储在S3上。
我的原始(阻塞)代码看起来像这样
# From DownloadsController#download data = open(path) send_data(data.read, type: @download.mime_type, filename: @download.file_title)所以我设置了Redis和Sidekiq,并创建了一个FielDownloadWorker :
class FileDownloadWorker include Sidekiq::Worker def perform(path, mime_type, file_title) data = open(path) # What happens next? end end使用以下内容称为:
FileDownloadWorker.perform_async(path,@ download.mime_type,@ download.file_title)
如何从工作人员开始下载?
I'm trying to break out file download into a background process. My assets are stored on S3.
My original (blocking) code looks like this
# From DownloadsController#download data = open(path) send_data(data.read, type: @download.mime_type, filename: @download.file_title)So I've set up Redis and Sidekiq, and Created a FielDownloadWorker:
class FileDownloadWorker include Sidekiq::Worker def perform(path, mime_type, file_title) data = open(path) # What happens next? end endWhich is called using:
FileDownloadWorker.perform_async(path, @download.mime_type, @download.file_title)
How do I initiate download from the worker?
最满意答案
你不能。 您希望用户收到该文件,对吗? 它必须在控制器内发生,以便控制器可以响应下载。 如果您正在尝试实现并发尝试使用线程:
@data = nil t = Thread.new { @data = open(path) } # ... do other stuff ... t.join # wait for download to finish in other thread send_data(@data.read, type: @download.mime_type, filename: @download.file_title)如果您决定采用工作方法,则可以在下载完成后更新数据库字段或缓存,然后用户必须向您的应用程序发出另一个请求以获取完成的文件。 就像是:
用户单击按钮以启动下载。 页面更新消息“您的文件正在下载,几秒钟后刷新页面” 用户刷新页面,控制器看到文件已下载并执行send_dataI ended up initiating the file download directly from S3 using Query String Authentication. This way the file is downloaded directly to the client from S3 and the Rails app's thread isn't blocked.
Great writeup here.
更多推荐
发布评论