There are several commands related to Redis transactions:
multi: mark the start of a block of transactionsexec: execute all commands in a block of transactions started by multidiscard: cancel the transaction, discard all commands within the block of transactions started by multiwatch: monitor one or more keys, if these keys are modified by other clients before the transaction is executed, the execution of the transaction will failunwatch: cancel all watch commands to monitor keys in a redis transaction, Multiple commands are combined into a single block of transactions and executed sequentially, and requests from other clients do not interfere with the execution of the Redis transaction during execution. When an exec command is executed, Redis will execute all commands in the previously committed transaction to all connected clients.
Redis transaction blocks are not the same as the transaction concept in traditional databases, and redis transaction blocks do not guarantee atomicity by themselves, but after special processing, all commands in the transaction block are either executed or none are executed.
Here are some examples of commands related to Redis transactions:
1. Use the multi and exec commands to submit a simple transaction block:
multiset key1 value1set key2 value2exec
This will result in two consecutive set commands, which are marked as a block of transactions, and then submitted for execution via the exec command.
2. Use the watch command to monitor the key and simulate the CAS (check and set) behavior
watch key1val1 = get key1val1 = val1 + 1multiset key1 val1exec
The above operation monitors the key key1 with the watch command, then performs a get operation on key1, then executes a plus 1 operation, marks a transaction block and executes a set operation in it, and finally commits the transaction block.
If another client modifies the value of key1 during the operation, the execution of the transaction block will fail and an empty list will be returned.
3. Use the discard command to cancel the transaction block
multiset key3 value3discard
The above operation uses the multi command to mark a block of transactions, followed by a set command. Then use the discard command to cancel the current transaction block, at which point the set command will not be executed, and key3 will not be set.