1、理论
1.1 概念
Redis事务与数据库的事务不同,它只有两个特性。
引用原著:
All the commands in a transaction are serialized and executed sequentially. A request sent by another client will never be served in the middle of the execution of a Redis Transaction
保证队列中的命令按照添加的顺序执行。
The EXEC command triggers the execution of all the commands in the transaction, so if a client loses the connection to the server in the context of a transaction before calling the EXEC command none of the operations are performed, instead if the EXEC command is called, all the operations are performed
Exec命令触发队列中所有命令的执行,若在之前发生异常情况,所有命令都不会执行,在中途某个命令执行失败,不会影响其他命令的执行。
1.2 步骤
第一步,开启事务,执行multi命令。
第二步,添加命令到队列中,此时不会检查语法错误。
第三步,执行exec,命令依次执行。若在此之前执行discard,或发生异常情况,事务被丢弃。
1.3 错误情况
在exec之前发生错误,例如命令语法不正确,watch的字段被修改,或者内存溢出等等。这些异常事务直接被丢弃。
在exec之后发生异常,某条命令执行失败,客户端失去连接等等,这些情况只会影响某个命令。
2、操作
2.1 discard
它的含义是丢弃事务。在exec命令之前执行。
示例:
// 开启事务 multi // 添加1到n条命令到队列。 cmd 1, cmd2, cmd n // 丢弃 discard // 此时exec不会执行 exec
2.2 watch
引用原著:
watched keys are monitored in order to detect changes against them. If at least one watched key is modified before the EXEC command, the whole transaction aborts, and EXEC returns a Null reply to notify that the transaction failed.
在exec命令之前,观察某些key值,若它们被修改,则丢弃事务。
修改的含义有:删除,key过期,key的值被更新,若是容器型,如list, set, zset,hash,还包含添加和删除元素。
乐观锁的概念略。
示例:
// watch 任意一个键值。 WATCH mykey // 开启事务 MULTI // 1到多条命令 cmd1, cmd2, cmdN // 执行 EXEC
2.3 unwatch
unwatch是watch的逆向操作。两种格式。
第一种,unwatch,无key参数,会unwatch所有key。
第二种,unwatch key1, key2... keyN,unwatch一到多个key值。
其他情况下也会导致unwatch。原著中提到两种场景。
第一种,客户端失去连接,此时该客户端的所有被观察的key值都会失效。重新连接不会恢复。
第二种,key值过期,key值被删除等,watch自动失效。