Redis transaction
Redis transactions can execute multiple commands at once, and come with the following two important guarantees:
A transaction is a single isolated operation: within a transaction All commands will be serialized and executed in order. During the execution of the transaction, it will not be interrupted by command requests sent by other clients.
A transaction is an atomic operation: either all commands in the transaction are executed, or none of them are executed.
A transaction will go through the following three stages from start to execution:
Start transaction.
Command to join the queue.
Execute transactions.
Example
The following is an example of a transaction. It starts a transaction with MULTI and then queues multiple commands. into the transaction, and finally the transaction is triggered by the EXEC command, and all commands in the transaction are executed 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"
Redis transaction commands
The following table lists Redis transaction related commands:
Serial number | Command and description |
---|---|
1 | DISCARD Cancel the transaction and give up executing all commands in the transaction block. |
2 | EXEC Execute all commands within the transaction block. |
3 | MULTI Marks the beginning of a transaction block. |
4 | UNWATCH Cancel the monitoring of all keys by the WATCH command. |
5 | WATCH key [key ...] Monitor one (or more) keys, if this (or these) keys are executed before the transaction If modified by other commands, the transaction will be interrupted. |