May 15, 2016
This blog is part of our Rails 5 series.
Before Rails 5 we had ability to configure Active Job queue_adapter
at an
application level. If we want to use sidekiq
as our backend queue adapter we
would configure it as following.
config.active_job.queue_adapter = :sidekiq
This queue_adapter
would be applicable to all jobs.
Rails 5 provides ability to configure queue_adapter
on a per job basis. It means
queue_adapter
for one job can be different to that of the other job.
Let's suppose we have two jobs in our brand new Rails 5 application. EmailJob
is responsible for processing basic emails and NewsletterJob
sends out news
letters.
class EmailJob < ActiveJob::Base
self.queue_adapter = :sidekiq
end
class NewletterJob < ActiveJob::Base
end
EmailJob.queue_adapter
=> #<ActiveJob::QueueAdapters::SidekiqAdapter:0x007fb3d0b2e4a0>
NewletterJob.queue_adapter
=> #<ActiveJob::QueueAdapters::AsyncAdapter:0x007fb3d0c61b88>
We are now able to configure sidekiq
queue adapter for EmailJob
. In case of
NewsletterJob
we fallback to the global default adapter which in case of a new
Rails 5 app is async.
Moreover, in Rails 5, when one job inherits other job, then queue adapter of the parent job gets persisted in the child job unless child job has configuration to change queue adapter.
Since news letters are email jobs we can make NewsLetterJob
inherit from
EmailJob
.
Below is an example where EmailJob
is using rescue
while NewsLetterJob
is
using sidekiq
.
class EmailJob < ActiveJob::Base
self.queue_adapter = :resque
end
class NewsletterJob < EmailJob
end
EmailJob.queue_adapter
=> #<ActiveJob::QueueAdapters::ResqueAdapter:0x007fe137ede2a0>
NewsletterJob.queue_adapter
=> #<ActiveJob::QueueAdapters::ResqueAdapter:0x007fe137ede2a0>
class NewsletterJob < EmailJob
self.queue_adapter = :sidekiq
end
NewsletterJob.queue_adapter
=> #<ActiveJob::QueueAdapters::SidekiqAdapter:0x007fb3d0b2e4a0>
If this blog was helpful, check out our full blog archive.