乐观锁使用场景1:
业务流程状态发生变化: 比如 订单状态变更,从0 (初始状态) 变更成 1(已完成)
正常sql逻辑 : update order set status = 1 where id = 1 ;
加入乐观锁sql逻辑; update order set status = 1 where id = 1 and status =0 ;
如果订单状态已经发生变化了,这个乐观锁的sql肯定执行结果是0 ,说明这个请求是重复的或者异常的请求,直接回滚即可。如果未使用乐观锁,假如这时候订单状态已更新成2 (已取消),又会把订单更新成1 。
乐观锁使用场景2:
当金额发生减少时候避免金额减成负数:比如 account账户余额1000,付款减余额1000。
正常sql逻辑1:
select Balance from account where id =1;
int M = Balance -1000;
update account set Balance = M where id =1;
正常sql逻辑2:
update account set Balance = Balance -1000 where id =1;
乐观锁sql逻辑: update account set Balance = Balance -1000 where id =1 and Balance -1000 >=0 ;