数据库事务二阶段提交(更新丢失问题)问题复现和解决

数据库事务二阶段提交(更新丢失问题)问题复现和解决

    数据埋点 t_amout
    
    userId       userName      Amount
    0001        张三        100        
    0002        李四        500

    事务A业务:0001向0002转账30元,返回异常情况 1.余额不足 2.系统异常
    事务A业务:0001向0002转账50元,返回异常情况 1.余额不足 2.系统异常

    事务A:select * from t_amout where userId=0001;  amount 100
    事务B: select * from t_amout where userId=0001;  amount 100
    事务A:  update t_amout set amount=100-30 where userId=0001;
            update t_amout set amount=amount+30 where userId=0002;
            commit;
    事务B:update t_amout set amount=100-50 where userId=0001;
           update t_amout set amount=amount+50 where userId=0002;
           commit;
           
    现象:0001目前还有50元
    
    解决方案:
    1:乐观锁自旋
       给数据加一个版本号,事务A更新之后,事务B更新会失败.就会自旋一次,重新查找,重新更新.
       这种同时转账情况还是较少,而且自旋几次对于用户来说还是无感知的.
    2:悲观锁
        事务A:select * from t_amout where userId=0001 for update;  Mysql会一直阻塞 Oracle有一点改变,可以指定阻塞时间.
posted @ 2022-08-19 15:57  苏子墨  阅读(88)  评论(0)    收藏  举报