使用Sidekiq将文件下载到后台进程中(Break Out File Download into Background Process Using Sidekiq)

编程入门 行业动态 更新时间:2024-10-23 13:28:25
使用Sidekiq将文件下载到后台进程中(Break Out File Download into Background Process Using Sidekiq)

我正在尝试将文件下载分解为后台进程。 我的资产存储在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 end

Which 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_data

I 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.

更多推荐

本文发布于:2023-08-06 07:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   进程   文件   Sidekiq   Break

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!