Redis事务
Redis事务是一个单独的隔离操作,事务中所有的命令都会序列化、按顺序执行,事务在执行的过程中不会被其它客户端发送过来的命令所打断.
Redis同一事务中如果有一条命令执行失败,其它的命令仍然会被执行,没有回滚.
Redis事务的主要作用是串联多个命令,防止别的命令插队.
dadas
dada
a
sdada
dassd
一、Redis正常开启事务,执行事务.
127.0.0.1:6379> multi
OK
127.0.0.1:6379> hincrby role role:9527:age 2
QUEUED
127.0.0.1:6379> hincrby role role:9527:age 3
QUEUED
127.0.0.1:6379> hincrby role role:9527:age -5
QUEUED
127.0.0.1:6379> exec
1) (integer) 24
2) (integer) 27
3) (integer) 22
二、Redis放弃事务.
127.0.0.1:6379> multi
OK
127.0.0.1:6379> hmset role role:9527:birthday 1992-10-10
QUEUED
127.0.0.1:6379> hexists role role:9527:id
QUEUED
127.0.0.1:6379> hkeys role
QUEUED
127.0.0.1:6379> discard
OK
三、Redis在事务队列中存在语法性错误(类似于java中的运行时异常),则执行exec命令时,正确的命令会被执行,错误的命令会抛出异常.
127.0.0.1:6379> multi
OK
127.0.0.1:6379> hkeys role
QUEUED
127.0.0.1:6379> hvals role
QUEUED
127.0.0.1:6379> hincrby role role:9527:name 3
QUEUED
127.0.0.1:6379> exec
1) 1) "role:9527:id"
2) "role:9527:name"
3) "role:9527:age"
2) 1) "9527"
2) "xiaomaomao"
3) "22"
3) (error) ERR hash value is not an integer
四、Redis在事务队列中出现命令性异常(类似于java中的编译期异常),则执行exec命令的时候所有命令都不会执行.
127.0.0.1:6379> multi
OK
127.0.0.1:6379> hexists role role:9527:name
QUEUED
127.0.0.1:6379> hget role
(error) ERR wrong number of arguments for ‘hget‘ command
127.0.0.1:6379> hsetnx role role:9527:gender female
QUEUED
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
原文:https://www.cnblogs.com/xiaomaomao/p/13393411.html