Redis6 transaction operation
1 Redis transaction definition
Redis transaction is a separate isolation operation, and all commands in the transaction will be serialized and executed sequentially. During the execution of the transaction, it will not be interrupted by commands sent by other clients.
The main function of Redis transactions is to connect multiple commands in series to prevent other commands from jumping into the queue.
2 Multi、Exec、Discard
Starting from the input of the Multi command, the input commands will enter the command queue in turn, but will not be executed until the Exec is entered, Redis will execute the commands in the previous command queue in turn, and the team can be discarded during the team formation process. .
3 transaction error handling
If a command in the team fails, the entire queue command will be canceled during execution
In the execution stage, if a command fails, only the command that reports the error will not be executed, and other commands will be executed normally.
Since the value of k1 is not a number, the incr self-increment fails
4 locks
(1) Pessimistic lock
Pessimistic locking means that data will have thread safety issues before sharing, so lock it first, and others who want to use this data must wait for the lock to be released first. Traditional relational databases use many such locking mechanisms, such as row locks, table locks, read locks, and write locks. This way is very inefficient
(2) Optimistic lock
Optimistic locking, every time you get the data, you think that others will not modify it, so you don’t lock it, but when updating, you will judge whether someone has updated the data during this period, and you can use mechanisms such as version numbers. Optimistic locking is suitable for multi-degree application types and can improve throughput. Redis uses this check-and-set mechanism to implement transactions
Perform an optimistic lock test on two terminals. Both terminals watch balance. Then terminal 1 adds 10 to balance and joins the transaction queue. Terminal 2 adds 20 to balance and joins the transaction queue. Terminal 1 first Execute the transaction, add 10 successfully, and the execution of terminal 2 will be invalid
Use the unwatch command to cancel monitoring
5 Three characteristics of Redis transactions
(1) Separate isolation operation:
Redis transaction is a separate isolation operation, and all commands in the transaction will be serialized and executed sequentially. During the execution of the transaction, it will not be interrupted by commands sent by other clients.
(2) There is no concept of isolation level:
The commands in the queue will not be executed until they are submitted
(3) Atomicity is not guaranteed
If a command fails to execute in the transaction, other commands will still be executed without rollback