redis的事务
redis事务命令:
Discard:取消事务,放弃执行事务块内的所有命令
exec:执行所有事务快内的命令
multi:标记一个事务块的开始
UNwatch:取消watch命令对所有key的监视
watch key(key ,,)
监视一个或者多个key,如果在事务执行之前这个或这些key被其他命令所改动,那么事务将被打断
MULTI可以执行多个命令,只要命令正确就行,正确执行
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> get k2
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) "v2"
4) OK
放弃事务 DISCARD
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 22
QUEUED
127.0.0.1:6379> set k3 33
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> get k2
"v2"
全体连坐:
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> getset k3
(error) ERR wrong number of arguments for 'getset' command
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
冤有头债有主,谁错不执行,其他的继续执行
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> incr k1
QUEUED
127.0.0.1:6379> set k2 22
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> set k4 v4
QUEUED
127.0.0.1:6379> EXEC
1) (error) ERR value is not an integer or out of range
2) OK
3) OK
4) OK
WATCH的方法先watch,然后再把balance改为800,再开启事务,让balance减少20,debt增加20,exec后事务失败
127.0.0.1:6379> WATCH balance
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> DECRBY balance 20
QUEUED
127.0.0.1:6379> INCRBY debt 20
QUEUED
127.0.0.1:6379> EXEC
(nil)
127.0.0.1:6379> get balance
"800"
127.0.0.1:6379> set balance 800
OK
unwatch:取消watch命令对所有key的监视
127.0.0.1:6379> get balance
"500"
127.0.0.1:6379> get debt
"20"
127.0.0.1:6379> WATCH balance
OK
127.0.0.1:6379> set balance 500
OK
127.0.0.1:6379> UNWATCH
OK
127.0.0.1:6379> WATCH balance
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> set balance 80
QUEUED
127.0.0.1:6379> set debt 20
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK