The transaction
Pipeline and serialization modes In the presence of multiple clients, commands from different clients may be executed alternately.
In this case, a client cannot implement atomization of commands executed in batches, so redis transactions are required to implement atomization.
Concept: a client transaction expects commands to be executed atomically, without other commands.
Implementation: After the client enables the transaction command, the sent commands are temporarily stored in the queue of the server. After all the commands are sent, they are executed in batches. Because Redis executes commands single-threaded, you can be sure that no other client commands will be executed.
The distinction between read and write commands in transactions and the problems caused by:
The client should determine the value of each write command when enqueuing, that is, it cannot rely on the execution results of other commands. Transaction operations require read-only operations to determine what value is being written. But the only things in the queue that need to be done in batches are writes, because it makes no sense to do read-only operations in batches. The client needs to execute the read command first, determine the value to be written, and then execute the transaction. However, it is possible for other clients to change previously read records.
Redis implements optimistic locking to solve this problem:
1. Add the key involved in the transaction to the observer mode Watch
2. Perform the read-only operation
3. The client sets the write operation value based on the read-only operation
4. Send the write command to queue
5. Batch submission. If the watch key is modified before, exec fails and refuses to execute.
Note:
Redis transactions cannot achieve strict consistency: when a command in a transaction starts exec execution, if an error occurs, subsequent commands will continue to execute, only marking the error command and result on return, and the client decides how to recover. Redis itself does not support rollback, so there is no need to introduce a versioning mechanism.