rails中使用sidekiq
蔡源茂 | 创建:2018-06-04 | 最后更新:2018-06-05 | 2161次阅读
前提:
需要先安装reids,参考Redis安装指南
1. 在gemfile中,增加
gem 'sidekiq'
2. rails配置中指定队列适配器
#rails 5.1
#/config/application.rb
class Application < Rails::Application
config.active_job.queue_adapter = :sidekiq
end
3. 配置sidekiq(可选)
#/config/sidekiq.yml
:concurrency: 20
:pidfile: tmp/pids/sidekiq.pid
:logfile: log/sidekiq.log
:queues:
- [notifications, 100] #此处数值仅表示权重
- [mailer, 5]
- [default, 3]
配置过sidekiq后,可在job中使用定义好的队列
class NotifyCommentJob < ApplicationJob
queue_as :notifications #notifications队列需要在sidekiq.yml文件中定义。未定义时,可使用默认队列default
def perform(*args)
# 稍后做些事情
end
end
4. 启动sidekiq
启动sidekiq后,相当于另起了一个rails进程,只不过该进程仅用于执行队列任务。
默认使用develop模式启动,启动生产模式指令为:bundle exec sidekiq -e production
网上很多人 写的加参数-C config/sidekiq.yml
可以忽略不写,但我发现rails 5.0 以后的版本 默认即加载config/sidekiq.yml
#bundle exec sidekiq
caiyuanmao@caiyuanmao:~/blog$ bundle exec sidekiq
m,
`$b
.ss, $$: .,d$
`$$P,d$P' .,md$P"'
,$$$$$bmmd$$$P^'
.d$$$$$$$$$$P'
$$^' `"^$$$' ____ _ _ _ _
$: ,$$: / ___|(_) __| | ___| | _(_) __ _
`b :$$ \___ \| |/ _` |/ _ \ |/ / |/ _` |
$$: ___) | | (_| | __/ <| | (_| |
$$ |____/|_|\__,_|\___|_|\_\_|\__, |
.d$$ |_|
2018-06-04T09:41:19.593Z 5350 TID-1911wk INFO: Running in ruby 2.4.1p111 (2017-03-22 revision 58053) [i686-linux]
2018-06-04T09:41:19.593Z 5350 TID-1911wk INFO: See LICENSE and the LGPL-3.0 for licensing details.
2018-06-04T09:41:19.593Z 5350 TID-1911wk INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org
2018-06-04T09:41:19.593Z 5350 TID-1911wk INFO: Booting Sidekiq 5.1.3 with redis options {:id=>"Sidekiq-server-PID-5350", :url=>nil}
2018-06-04T09:41:19.595Z 5350 TID-1911wk INFO: Starting processing, hit Ctrl-C to stop
5. 使用自带的监控页面(可选)
在路由中,增加查看sidekiq的路由
#/config/routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
mount Sidekiq::Web => '/sidekiq'
end
网址:http://localhost:3000/sidekiq/busy
如果需要在这条路由上增加权限控制的话,可以利用constraints给sidekiq路由增加如下约束:
#/config/routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
mount Sidekiq::Web => '/sidekiq', constraints: -> (request){
user = User.find_by_id(request.session[:user_id])
user && user.admin?
}
end
如果你使用的devise,那么可以使用如下方式
authenticate :user do
mount Sidekiq::Web => '/sidekiq'
end
如果你定义了 User#admin? 方法,则可以进一步修改成:
authenticate :user , ->(u) { u.admin? } do
mount Sidekiq::Web => '/sidekiq'
end
参考链接: