Redis's current support for transactions is relatively straightforward, and redis guarantees that commands in a client-initiated transaction can be executed consecutively without inserting other client commands; When a client initiates a multi command in a connection, The connection goes into the transaction context, and the subsequent commands are not executed immediately, but instead are placed in a queue, and Redis executes all the commands in that queue sequentially when the EXEC command is executed.
The command keyword involved in redis transactions: MULTI enters a transaction context, EXEC executes the transaction, DISCARD rolls back the transaction, Watch transaction optimistic lock
A transaction in SQL Server or Mysql (the transaction is completely rolled back when an error occurs in the operation of the transaction). But there are some things that are different in Redis.
You can see from the following command execution:
127.0.0.1:6379> Set age 10
Ok
127.0.0.1:6379> Set name Hexu
Ok
127.0.0.1:6379> Multi
Ok
127.0.0.1:6379> incr Age
QUEUED
127.0.0.1:6379> incr Name
QUEUED
127.0.0.1:6379> exec
1) (integer) 11
2) (Error) ERR value is not a integer or out of range
127.0.0.1:6379> Get Age
"11"
127.0.0.1:6379> Get Name
"Hexu"
Key["Age"] is a int,key["name"] is a string, when we increment the name by the INCR command, name error, and finally we execute the EXEC command, the result of the time does not roll back. This is where redis needs to be improved.
Transaction optimistic Lock
The watch command monitors the given key, and when exec does, the entire transaction fails if the monitored key has changed.
When there are multiple sessions, Seesion1 first turns on the transaction and assigns an age value of 100, at which time the transaction is temporarily not exec. The Session2 uses a non-transactional method to assign an age value of 120 and the assignment is complete. Then Session1 executes the EXEC command. When a key is added to an optimistic lock, the transaction fails to execute.
Session1:
127.0.0.1:6379> WATCH Age First step
Ok
127.0.0.1:6379> MULTI Second Step
Ok
127.0.0.1:6379> set age 100 Third step
QUEUED
127.0.0.1:6379> EXEC Step Fifth
(nil)
Session2:
127.0.0.1:6379> set Age 120 Fourth step
Ok
Using the Exec,discard,unwatch command clears the monitoring in the connection
Four. Redis transaction processing