- All commands in a transaction are serialized and executed sequentially.
- The transaction will not be interrupted by command requests from other clients during execution.
The transaction
Multi: Marks the start of a transaction block. Subsequent instructions will be executed as an atom during EXEC execution.
Normal execution transactions
127.0.0.1:6379, 6379: > multi OK 127.0.0.1 (TX) >setK1 1 QUEUED 127.0.0.1:6379 (TX) >setK2 2 QUEUED 127.0.0.1:6379(TX)> get k2 QUEUED 127.0.0.1:6379(TX)>exec
1) OK
2) OK
3) "127.0.0.1:6379> get k1"1"
127.0.0.1:6379>
Copy the code
Give up the transaction
127.0.0.1:6379, 6379: > multi OK 127.0.0.1 (TX) >setK3 3 QUEUED 127.0.0.1:6379(TX)> discard OK 127.0.0.1:6379> get K3 (nil) 127.0.0.1:6379>Copy the code
Exception at compile time all commands are not executed
127.0.0.1:6379, 6379: > multi OK 127.0.0.1 (TX) >setK3 3.0 QUEUED 127.0.0.1:6379(TX)> getSet KKK (error) ERR wrong number of argumentsfor 'getset' command127.0.0.1:6379 (TX) >exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get k3
(nil)
127.0.0.1:6379>
Copy the code
Runtime exception Other commands run as usual, error commands throw exceptions
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> set k1 "hello"
QUEUED
127.0.0.1:6379(TX)> incr k1
QUEUED
127.0.0.1:6379(TX)> setK2 v2 QUEUED 127.0.0.1:6379 (TX) >setK3 v3 QUEUED 127.0.0.1:6379(TX)> get K3 QUEUED 127.0.0.1:6379(TX)>exec
1) OK
2) (error) ERR value is not an integer or out of range
3) OK
4) OK
5) "v3"127.0.0.1:6379 > get k3"v3"127.0.0.1:6379 >Copy the code
Watch optimistic locking
When EXEC is invoked, monitoring of all keys is removed, regardless of whether the transaction executes successfully.
In addition, when the client disconnects, the client’s monitoring of the key is also removed.
127.0.0.1:6379 > watch money# monitoring money
OK
# Change money on the other client
# 127.0.0.1:6379> set money 1000
# OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> get money
QUEUED
127.0.0.1:6379(TX)> setMoney 100 QUEUED 127.0.0.1:6379 (TX) >exec
(nil) # failed to execute127.0.0.1:6379 > get the money"1000"127.0.0.1:6379, 6379: > multi OK 127.0.0.1 (TX) >setMoney 200 QUEUED 127.0.0.1:6379 (TX) >exec
1) OK
127.0.0.1:6379> get money
"200"127.0.0.1:6379 >Copy the code