我自己正在学习数据库事务设计并遇到了这个问题。问题是从将资金从 src_account 转移到 dst_account 的代码片段中查找问题。下面的代码是我给出的解决方案。有人可以帮我检查我的解决方案是否有问题吗?我是否在正确的位置提交、回滚、启动事务?我需要为读取添加提交吗?锁应该在表级别还是索引级别?这被认为是两相锁定吗?有什么我们可以异步做来提高性能的吗?非常感谢!
bank_transfer(src_account, dst_account, amount):
try:
src_account.lock()
src_cash = src_account.cash # DB read
dst_account.lock()
dst_cash = dst_account.cash # DB read
if src_cash < amount:
raise InsufficientFunds
with db_transaction(level = serializable):
src_account.cash = src_cash - amount # DB write
dst_account.cash = dst_cash + amount # DB write
commit
src_account.send_src_transfer_email()
dst_account.send_dst_transfer_email()
except Exception as e:
logger.error()
handle_exception(e)
abort()
rollback()
finally:
src_account.unlock() # release lock, no matter what
dst_account.unlock()