This option implies that jobs of one context are executed sequentially in one queue, and jobs of different contexts in parallel in different queues.
Let's look at the following example.
There are investment funds for which we want to make time-consuming reporting calculations. Jobs for calculation within the same fund are carried out sequentially so that there are no errors in the calculations, jobs of different funds are performed in parallel.
We automate the distribution of jobs in queues so as not to specify a queue manually.
Specify the queues in the sidekiq.yml
configuration file:
:queues:
- fund_processor_0
- fund_processor_1
- fund_processor_2
- fund_processor_3
- fund_processor_4
It is important that the queues are numbered from 0.
Now, when starting the worker, we indicate in which queue we will set the job depending on the fund. To do this, we use the operation of obtaining the remainder from dividing the fund ID and the count of queues. So we get the queue number.
# 5 queues
# fund ID % count of queues = queue number
# 1 % 5 => 1
# 2 % 5 => 2
# 3 % 5 => 3
# 4 % 5 => 4
# 5 % 5 => 0
def queue_name(fund_id)
queue_number = fund_id % 5
"fund_processor_#{queue_number}"
end
Start the worker, indicating to him the received queue name.
This can be done using the Sidekiq API
Sidekiq::Client.push(
'queue' => queue_name(fund_id),
'class' => Fund::ReportCalculator,
'args' => [fund_id]
)
Top comments (0)