Redis事务:
在一个队列(queue)中依次执行一系列的命令。
事务的三个阶段:
1.开始事务(MULTI)
2.命令加入队列 (QUEUE)
3.执行事务 (EXEC)
示例1:
MULTI > QUEUE > EXEC(一般情况下依次执行队列中所有命令)
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) OK
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
127.0.0.1:6379>
示例2:
MULTI > QUEUE > DISCARD(取消执行队列中的所有命令)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> set k5 v5
QUEUED
127.0.0.1:6379> set k6 v6
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
127.0.0.1:6379>
示例3:
MULTI > QUEUE > EXEC(QUEUE中的命令有错误,所有命令不执行)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> set k5
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379> set k6
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
3) "k1"
127.0.0.1:6379>
示例4:
MULTI > QUEUE > EXEC(QUEUE中的命令执行失败,其余命令正常执行)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> incr k4
QUEUED
127.0.0.1:6379> set k5 v5
QUEUED
127.0.0.1:6379> set k6 v6
QUEUED
127.0.0.1:6379> exec
1) OK
2) (error) ERR value is not an integer or out of range
3) OK
4) OK
127.0.0.1:6379> keys *
1) "k6"
2) "k1"
3) "k2"
4) "k3"
5) "k4"
6) "k5"
127.0.0.1:6379>
示例5:
WATCH > MULTI > QUEUE > EXEC
1.如果事务执行前WATCH的key被其他进程操作了,事务执行失败;
2.EXEC执行后不管事务是否执行成功,WATCH都会解除;
3.UNWATCH可以手动解除WATCH。
客户端1
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> watch k1
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> append k1 xyz
QUEUED
127.0.0.1:6379>
客户端2
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> append k1 abc
(integer) 5
127.0.0.1:6379> get k1
"v1abc"
127.0.0.1:6379>
客户端1
127.0.0.1:6379> exec
(nil)
127.0.0.1:6379>