iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

Ruby on Rails 與它們相關的東西 II系列 第 8

Day08 - Gem-sidekiq-grouping 允許單個 sidekiq 處理多個相似(一樣)的 jobs

前言

Allows identical sidekiq jobs to be processed with a single background call

上述引用自 sidekiq-grouping,能將多個同 queue 的 worker 整合成一個處理

說明

直接以情境舉例,假如要打 API 更新第三方庫存數量,由於更新商品數量有加也有減,因此先 grouped 起來,整合成一個 job 處理

實作

在 Gemfile 中加入該 sidekiq-grouping,範例可參考此 pr

# config/routes.rb
require "sidekiq/grouping/web"

---

# app/worker/flush_worker.rb
class FlushWorker
  include Sidekiq::Worker

  sidekiq_options(
  retry: false,
  batch_flush_size: 5,      # 當 Jobs 數量超過 5 個時,將合併作業
  batch_flush_interval: 30, # 每 30 秒合併作業一次
  batch_unique: true,       # 同參數是否要 unique,無指定預設為 false
  )

  def perform(groups = nil)
    puts "args: #{groups}"
    puts "execute #{self.class}"
  end
end

接著在 rails console 輸入

# 當 batch_unique: true
10.times { FlushWorker.perform_async(1) }
# args: [[1]]


# 當 batch_unique: false or 沒指定
10.times { FlushWorker.perform_async(1) }
# args: [[1], [1], [1], [1], [1]]


10.times { |t| FlushWorker.perform_async(t) }
# args: [[0], [1], [2], [3], [4]]
# args: [[5], [6], [7], [8], [9]]

batch_unique: true

batch_unique: false 或沒寫

Web UI

routes.rb 檔案中加入 require "sidekiq/grouping/web"

小結

蠻好上手的一個 Gem,在 GitHub 的範例也寫得淺顯易懂,連測試也有範例,這邊就不多加贅述

參考資料

  1. sidekiq-grouping GitHub
  2. sidekiq-grouping, 允許使用單個後台調用處理相同的sidekiq作業

鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10264578
medium 文章連結:https://link.medium.com/0SSdkIm2Mjb
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主


上一篇
Day07 - Gem-sidekiq-limit_fetch 限制 sidekiq queue 執行數量
下一篇
Day09 - Gem-jwt 介紹與應用
系列文
Ruby on Rails 與它們相關的東西 II30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言