在 Rails 專案中使用 Sidekiq 處理非同步任務
阿新 • • 發佈:2020-06-24
Sidekiq 是一個提供了執行 定時/非同步 任務的後臺任務處理系統,它可以整合在 Rails 專案中使用,也可以單獨的使用。在本篇文章中,我們將對如何在 Rails 中使用 Sidekiq 進行介紹和分析。
新增依賴
目前 Sidekiq 已經更新到 6.0 版本了,這裡我們使用最新的版本
$ gem install sidekiq
複製程式碼
gem 'sidekiq','~> 6.0','>= 6.0.3'
複製程式碼
修改配置
新增 config/sidekiq.yml
檔案
# 最大併發數
concurrency: 5
# 程式和日誌的輸出位置
pidfile: tmp/pids/sidekiq.pid
logfile: log/sidekiq.log
# 任務佇列
queues:
- default
- schedule
development:
concurrency: 5
staging:
concurrency: 10
production:
concurrency: 20
複製程式碼
新增 config/initializers/sidekiq.rb
檔案
# 設定 sidekiq cron 每秒鐘檢查一次任務,預設是 15 秒鐘檢查一次任務
Sidekiq.options[:poll_interval] = 1
Sidekiq.options[:poll_interval_average ] = 1
# 設定 sidekiq 服務端
Sidekiq.configure_server do |config|
# 配置 redis 連線
config.redis = { url: "redis://localhost:6379/0" }
# 設定 sidekiq 每秒鐘都會檢查一次作業(預設每5秒檢查一次)
config.average_scheduled_poll_interval = 1
# 從配置檔案中讀取定時任務
schedule_file = 'config/sidekiq_schedule.yml'
if File.exists?(schedule_file)
Sidekiq::Cron::Job.load_from_hash YAML.load_file(schedule_file)
end
end
Sidekiq.configure_client do |config|
config.redis = { url: "redis://localhost:6379/0" }
end
複製程式碼
在 config/application.rb
中設定配置項:
config.active_job.queue_adapter = :sidekiq # 使用 sidekiq 作為非同步任務的介面卡
複製程式碼
非同步任務
使用生成器來建立一個傳送訊息的任務:
$ rails g job SendMessage
複製程式碼
上面的命令將會建立 app/jobs/send_message_job.rb
class SendMessageJob < ActiveJob::Base
queue_as :default
def perform(*args)
Rails.logger.info "send message..."
end
end
複製程式碼
如何使用:
SendMessageJob.perform_async(xxx,xxx,xxx) # 建立非同步作業
SendMessageJob.perform_in(1.minutes,xxx) # 建立延時非同步作業
SendMessageJob.perform_at(1.minutes.from_now,xxx) # 指定時間建立非同步作業
複製程式碼
定時任務
新增 app/worker/send_message_worker.rb
檔案
class SendMessageWorker
include Sidekiq::Worker
sidekiq_options queue: :schedule,backtrace: true,retry: false
# 無需顯示呼叫,sidekiq 執行後會自動執行
# 傳入引數和執行週期在 config/sidekiq_schedule.yml 中配置
def perform(*args)
Rails.logger.info 'every second execution...'
end
end
複製程式碼
新增 config/sidekiq_schedule.yml
配置檔案
SendMessageWorker:
cron: '* * * * * *'
class: SendMessageWorker
複製程式碼
通過 sidekiq -C config/sidekiq
命令啟動,定時任務將會週期的執行
配置監控
sidekiq 在 4.2 以上版本已經內建了一套監控頁面,在 4.2 以前的版本需要新增額外的依賴:
gem 'sinatra','~> 2.0','>= 2.0.7'
複製程式碼
在 config/router.rb
檔案中掛載 WebUI 頁面的路由。
require 'sidekiq/web'
Rails.application.routes.draw do
mount Sidekiq::Web => '/sidekiq'
end
複製程式碼
rails s
啟動專案 sidekiq -C config/sidekiq.yml
啟動 sidekiq,訪問 http://localhost:3000/sidekiq