Redis Transactions
Redis transactions can execute multiple commands at once, and come with the following three important guarantees:
- Bulk operations are placed in a queue cache before the EXEC command is sent.
- After the EXEC command is received, the transaction enters execution. If any command in the transaction fails, the remaining commands are still executed.
- During transaction execution, command requests submitted by other clients will not be inserted into the sequence of commands executed in the transaction.
A transaction goes through the following three stages from start to execution:
- Begin transaction.
- Command queuing.
- Execute transaction.
Example
The following is an example of a transaction. It first usesMULTIto start a transaction, then queues multiple commands into the transaction, and finally usesEXECcommand to trigger the transaction, executing all commands in the transaction together:
redis 127.0.0.1:6379> MULTI OK redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days" QUEUED redis 127.0.0.1:6379> GET book-name QUEUED redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series" QUEUED redis 127.0.0.1:6379> SMEMBERS tag QUEUED redis 127.0.0.1:6379> EXEC 1) OK 2) "Mastering C++ in 21 days" 3) (integer) 3 4) 1) "Mastering Series" 2) "C++" 3) "Programming"
The execution of a single Redis command is atomic, but Redis does not add any mechanism to maintain atomicity to transactions, so the execution of Redis transactions is not atomic.
A transaction can be understood as a packaged batch execution script, but batch commands are not atomic operations. If one command in the middle fails, it will not cause rollback of previously executed commands, nor will it prevent subsequent commands from being executed.
This is the explanation on the official website. From redis docs ontransactions:
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.
For example:
redis 127.0.0.1:7000> multi OK redis 127.0.0.1:7000> set a aaa QUEUED redis 127.0.0.1:7000> set b bbb QUEUED redis 127.0.0.1:7000> set c ccc QUEUED redis 127.0.0.1:7000> exec 1) OK 2) OK 3) OK
If it fails at set b bbb, set a has already succeeded and will not be rolled back, and set c will continue to execute.
Redis Transaction Commands
The following table lists the commands related to Redis transactions:
| No. | Command and Description |
|---|---|
| 1 | DISCARD Cancel the transaction and abandon all commands in the transaction block. |
| 2 | EXEC Execute all commands in the transaction block. |
| 3 | MULTI Mark the start of a transaction block. |
| 4 | UNWATCH Cancel the monitoring of all keys by the WATCH command. |
| 5 | WATCH key [key ...] Watch one (or more) keys. If these keys are modified by other commands before the execution of the transaction, the transaction will be interrupted. |