悲观锁:
乐观锁:
Redis监视测试
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 # 监视 money 对象 OK 127.0.0.1:6379> multi # 事务正常皆数,数据期间没有发生变动,这个时候就正常执行成功! OK 127.0.0.1:6379> DECRBY money 20 QUEUED 127.0.0.1:6379> INCRBY out 20 QUEUED 127.0.0.1:6379> exec 1) (integer) 80 2) (integer) 20
测试多线程修改值,使用watch可以当作redis的乐观锁操作!
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 (nil)
如果修改失败,获取最新的值就好unwatch再watch