ActiveRecord 模型的互斥锁 [英] Mutex for ActiveRecord Model

查看:43
本文介绍了ActiveRecord 模型的互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户模型有一个讨厌的方法,不应为同一记录的两个实例同时调用.我需要连续执行两个 http 请求,同时确保任何其他线程不会同时对同一条记录执行相同的方法.

My User model has a nasty method that should not be called simultaneously for two instances of the same record. I need to execute two http requests in a row and at the same time make sure that any other thread does not execute the same method for the same record at the same time.

class User
  ...
  def nasty_long_running_method
    // something nasty will happen if this method is called simultaneously
    // for two instances of the same record and the later one finishes http_request_1
    // before the first one finishes http_request_2.
    http_request_1 // Takes 1-3 seconds.
    http_request_2 // Takes 1-3 seconds.
    update_model
  end
end

例如这会破坏一切:

user = User.first
Thread.new { user.nasty_long_running_method }
Thread.new { user.nasty_long_running_method }

但这没问题,应该被允许:

But this would be ok and it should be allowed:

user1 = User.find(1)
user2 = User.find(2)
Thread.new { user1.nasty_long_running_method }
Thread.new { user2.nasty_long_running_method }

确保同一记录的两个实例不会同时调用该方法的最佳方法是什么?

What would be the best way to make sure the method is not called simultaneously for two instances of the same record?

推荐答案

我发现了一个 gem 远程锁在为我的问题寻找解决方案时.是后端使用Redis的互斥解决方案.

I found a gem Remote lock when searching for a solution for my problem. It is a mutex solution that uses Redis in the backend.

它:

  • 可供所有进程访问
  • 不锁定数据库
  • 在内存中 -> 快速且无 IO

这个方法现在看起来像这样

The method looks like this now

def nasty
  $lock = RemoteLock.new(RemoteLock::Adapters::Redis.new(REDIS))
  $lock.synchronize("capi_lock_#{user_id}") do
    http_request_1
    http_request_2
    update_user
  end
end

这篇关于ActiveRecord 模型的互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆