Redis的事务
-
Redis的单条命令时保证原子性, 但是事务不保证原子性
-
Redis事务没有隔离级别的概念
-
事务命令:
- 开启事务 multi
- 执行事务 exec
- 取消事务 discard
测试
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set key1 aaa
QUEUED
127.0.0.1:6379> set key2 bbb
QUEUED
127.0.0.1:6379> get key2
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) "bbb"
异常
- 编译型异常 - 命令有错, 事务中的所有命令都不会被执行
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set key1 aaa
QUEUED
127.0.0.1:6379> aaaaaaaaaaaaaa #没有这条命令
(error) ERR unknown command `aaaaaaaaaaaaaa`, with args beginning with:
127.0.0.1:6379> set key2 bbb
QUEUED
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
- 运行时异常 - 语法性的错误, 其他命令仍然会执行
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set key1 aaa
QUEUED
127.0.0.1:6379> incr key1 #对字符串进行+1
QUEUED
127.0.0.1:6379> set key2 bbb
QUEUED
127.0.0.1:6379> exec
1) OK
2) (error) ERR value is not an integer or out of range
3) OK
乐观锁
- 正常执行的事务
127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set spent 0
OK
127.0.0.1:6379> watch money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 20
QUEUED
127.0.0.1:6379> incrby spent 20
QUEUED
127.0.0.1:6379> exec
1) (integer) 80
2) (integer) 20
- 执行失败的事务, watch的值在变化后执行失败, 需要先unwatch后再次watch获取最新值
#线程1
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 spent 10
QUEUED
127.0.0.1:6379>
#线程2
127.0.0.1:6379> set money 1000
OK
#线程1
127.0.0.1:6379> exec
(nil)
#关闭监视
127.0.0.1:6379> unwatch
OK