Introduction
It is possible to group commands together so that they are executed as a single transaction
Related commands
- DISCARD
- EXEC
- MULTI
- UNWATCH
- WATCH
- All the commands in a transaction are serialized and executed sequentially. It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a single isolated operation.
- Either all of the commands or none are processed, so a Redis transaction is also atomic.
Watch 命令用于监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断。Watch + Multi实际是一种乐观锁(CAS)。
Redis 事务可以一次执行多个命令, 并且带有以下三个重要的保证:
- 批量操作在发送 EXEC 命令前被放入队列缓存;
- 收到 EXEC 命令后进入事务执行,事务中任意命令执行失败,其余的命令依然被执行;
- 在事务执行过程,其他客户端提交的命令请求不会插入到事务执行命令序列中
一个事务从开始到执行会经历以下三个阶段:
- 开始事务;
- 命令入队;
- 执行事务。
单个 Redis 命令的执行是原子性的,但 Redis 没有在事务上增加任何维持原子性的机制,所以 Redis 事务的执行并不是原子性的。
事务可以理解为一个打包的批量执行脚本,但批量指令并非原子化的操作,中间某条指令的失败不会导致前面已做指令的回滚,也不会造成后续的指令不做。
It’s important to note that even when a command fails, all the other commands in the queue are processed – Redis will not stop the processing of commands.
Errors inside a transaction
During a transaction it is possible to encounter two kind of command errors:
A command may fail to be queued, so there may be an error before EXEC is called.
For instance the command may be syntactically wrong (wrong number of arguments, wrong command name, …), or there may be some critical condition like an out of memory condition (if the server is configured to have a memory limit using the maxmemory directive).
A command may fail after EXEC is called.
For instance since we performed an operation against a key with the wrong value (like calling a list operation against a string value).
Attention
Why Redis does not support roll backs?
However there are good opinions for this behavior:
Redis commands can fail only if called with a wrong syntax (and the problem is not detectable during the command queueing), or against keys holding the wrong data type: this means that in practical terms a failing command is the result of a programming errors, and a kind of error that is very likely to be detected during development, and not in production.
Redis is internally simplified and faster because it does not need the ability to roll back.