1. 乐观锁: 很乐观,认为什么时候都不会出现问题,所以不会上锁,更新数据的时候再去判断一下在此期间是否有人修改过数据
# 获取version
#对比version
2. redis实现乐观锁: watch, unwatch(不加key)
127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set out 0
OK
127.0.0.1:6379> watch money #监控
OK
127.0.0.1:6379> multi #开启事务
OK
127.0.0.1:6379> decrby money 10
QUEUED
127.0.0.1:6379> incrby out 10
QUEUED
127.0.0.1:6379> exec #执行事务,在此期间数据没被修改过,事务执行成功,同时使watch失效
1) (integer) 90
2) (integer) 10
在另一客户端在事务执行之前修改数据为1000
127.0.0.1:6379> get money
"100"
127.0.0.1:6379> watch money #监控数据
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 10
QUEUED
127.0.0.1:6379> incrby money 10
QUEUED
127.0.0.1:6379> exec #事务执行失败,并释放锁
(nil)
127.0.0.1:6379> watch money #重新监控
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 10
QUEUED
127.0.0.1:6379> incrby out 10
QUEUED
127.0.0.1:6379> exec
1) (integer) 990
2) (integer) 20
127.0.0.1:6379>