Sidekiq 什麼魔法

Yeng Tsan
4 min readAug 23, 2016

--

標題原本要下得很長,叫做

「sidekiq什麼魔法之我什麼都不會但我還是要寫篇blog」

as title,我真的什麼都還不會。我不了解redis、sidekiq之間的關係,我不知道為什麼打這幾行code後sidekiq就會跑起來。

但我決定先記錄下來,之後慢慢的新增這篇blog、讓他更完整。

開始囉

brew install redis
redis-server

接著,如果我們要將ActiveJob的非同步處理做設定,要透過config/environments/development.rb 切換使用sidekiq

config.active_job.queue_adapter = :sidekiq

上面這行的意思,是將active_job延後執行時,queue到哪個adapter的設定

接著,在 config/application.rb中加入設定,讓Rails 可以找到job檔案

config.eager_load_paths += %W( #{config.root}/app/jobs )

設定sidekiq設定 config/sidekiq.yml

---
:queues:
- default
- mailers

sidekiq 也提供了web UI,在Gemfile裡面加上

gem 'sinatra', '>= 1.3.0', :require => false

並在routes加入

require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'

p.s.有可能因為sinatra的版本問題產生衝突,最後我的解決方案是直接上sinatra的github上面抓master的版本

gem 'sinatra', github: 'sinatra'

以上即完成sidekiq的安裝,而要順利的將rails server跑起來,需要將redis、sidekiq執行起來

範例

很理所當然的,當我們建立一個「非同步」的空間,讓queue有地方放、等伺服器有空閒的時候執行,我們的首要任務是

「要有任務,才會有任務進到queue這回事」

讓我們創立一個任務吧!

class HardWorkerJob < ActiveJob::Base
queue_as :default
def perform
Rails.logger.info("user: yayaya")
Rails.logger.info("starting hard work...")
sleep(3)
Rails.logger.info("ending hard work...")
end
end

接著,要告訴Rails可以上哪邊找job(在config/environment/development)

config.eager_load_paths += %W( #{config.root}/app/jobs )

並且在需要執行HardWorkerJob的地方,加入

HardWorkerJob.perform_later

perform是job定義出來的method,而後面的_later則是rails 動態產生的方法,perform_now即是馬上執行出來;若是perform_later,則會依據 config/environment/development 的設定,去決定非同步的工作該怎麼執行

例如:

config.active_job.queue_adapter = :sidekiq

sidekiq的路還沒走完,現在只是剛綁好鞋帶準備出門,努力前進吧….LOL

資料參考:https://ihower.tw/rails4/background-process.html

bundle exec sidekiq -d -L log/sidekiq.log -C config/sidekiq.yml -e production

上面的code可以在將sidekiq process 跑在背景,其中每個參數的意思如下

-d, Daemonize process

-L, path to writable logfile

-C, path to YAML config file

-e, Application environment

--

--

Yeng Tsan
Yeng Tsan

Written by Yeng Tsan

Software developer, Career consultant, Product manager.開啟你的海外職涯,從日本開始 https://engineer.taiwan-career.com/

No responses yet