我正在尝试使用 Redis 和Redlock library锁定我的部分代码。
我在这里实现了它:
def perform(task_id, task_type)
lock_manager = Redlock::Client.new([ "redis://127.0.0.1:6379" ])
lock_key = "task_runnuer_job_#{task_type}_#{task_id}"
puts("locking! #{task_id}")
lock_task = lock_manager.lock(lock_key , 6 * 60 * 1000)
if lock_task.present?
begin
# Exec task...
Services::ExecTasks::Run.call task.id
ensure
puts("unlocking! #{task_id}")
lock_manager.unlock(lock_task)
end
else
puts("Resource is locked! #{lock_key}")
end
end
同时运行多个 Sidekiq 作业时,我得到的是以下日志:
"locking! 520"
"locking! 520"
"unlocking! 520"
"unlocking! 520"
当我的两个不应该一起执行的 520 任务以 1ms 的差异被调用时,就会发生这种情况。
然而,有时锁会按预期工作。
我检查了 Redis,它工作得很好。
有任何想法吗?谢谢!