gpt4 book ai didi

mysql - Rails + MySQL + Transactions + Locking,如何防止打开事务解锁表?

转载 作者:可可西里 更新时间:2023-11-01 06:50:03 24 4
gpt4 key购买 nike

在我的 Rails 代码中,我需要确认仅当某个记录的剩余数量超过 1 时才允许执行操作。出于这个原因,我需要锁定更新然后执行读取。我的 Rails 代码如下所示:

PaymentProfile.transaction do
profiles = PaymentProfile.lock("LOCK IN SHARE MODE").where(user_id: xxx)

if profiles.count > 1
#allow
else
#do not allow
end
end

理论上这很有效并且确实正确地锁定了行。但是,如果另一个请求遍历相同的代码路径,打开事务会删除我在另一个进程中取出的锁,从而破坏锁的目的。

来自 MySQL 文档:

Beginning a transaction also causes table locks acquired with LOCK TABLES to be released, as though you had executed UNLOCK TABLES. Beginning a transaction does not release a global read lock acquired with FLUSH TABLES WITH READ LOCK.

最佳答案

我假设另一个请求将由另一个进程处理,或者至少由另一个连接(到 MySQL)处理(抱歉,我对 Ruby-on-rails 一无所知)。

一个给定事务获取的锁不能被另一个事务释放。这就是锁的真正目的。作为the manual说:

UNLOCK TABLES explicitly releases any table locks held by the current session

如果我的假设是正确的,就没有什么可担心的。否则,如果两个请求可能同时使用同一个连接,那么这个架构就有些可疑了……

关于mysql - Rails + MySQL + Transactions + Locking,如何防止打开事务解锁表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17002791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com