Transactions
Redis's transactional capabilities allow users to wrap multiple commands, and then execute all the commands that are wrapped in a single, sequential manner. During the execution of a transaction, the server does not break the transaction and changes to execute other command requests, except that all commands in the transaction package
The server will not process other command requests until the execution is complete.
Command |
function |
MULTI |
Start a new transaction. |
DISCARD |
Discards a transaction. |
Exec |
Executes all the commands in the transaction. |
MULTI
Begins a transaction. After this command executes, all commands sent by the client to the database or database keys are not executed immediately, but are placed into a transaction queue and returned to QUEUED to indicate that the command has been queued.
DISCARD
Cancels the transaction and discards all commands in the transaction queue.
Exec
Executes all the commands in the transaction queue, in the order in which the commands are queued to the transaction queue. The complexity of the command is the sum of the complexity of all the commands in the queue. The return value of the command is a list that contains the return value of all executed commands in the transaction queue. optimistic Lock
Use locks to ensure data is correct
WATCH key [Key ...]
If the monitored key has been preempted by another client before the transaction commits (that is, before the EXEC command executes), the server rejects the client-committed transaction and returns nil as the transaction's reply.
Optimistic locks monitor locked data, and multiple clients can attempt to modify the data at the same time, where the client that first tries succeeds, and the client that tries later fails.
Pessimistic locks allow only one client to modify the data, while other clients need to wait for the client that is making the modification to complete before attempting to gain the right to modify.
For Redis with frequent read and write operations, optimistic locking can be used to avoid blocking clients: When a client fails to modify the data, it simply retries, and the process does not require any waiting.
Unwatch
Cancels the monitoring of all keys.