Skip to content

Latest commit

 

History

History
34 lines (24 loc) · 638 Bytes

active_record_with_lock.md

File metadata and controls

34 lines (24 loc) · 638 Bytes

ActiveRecord的lock老大说只是一个数据库锁,并不是线程锁

如 account.balance -= amount 要写成

** with_lock写法 **

Account.transition do
  account.with_lock do
    account.balance -= amount
    account.save!
  end
end

** lock!写法 **

Account.transition do
  account.lock!
  account.balance -= amount
  account.save!
end

加事务的目的是如果中途出错, 账户变动会回滚

加数据锁的目的是防止多个线程同时修改