I. Redis self-with transaction mechanism
Redis transactions are operated through the multi, EXEC, discard, watch, and Unwatch commands, as follows:
Open the transaction through the multi, then add any command to the queue, execute the queue command through exec, discard the transaction, give the lock mechanism through the watch, and cancel the monitoring of the key through the unwatch.
Example 1: General usage
127.0.0.1:6379> Multi
Ok
127.0.0.1:6379> incr AAA
QUEUED
127.0.0.1:6379> incr BBB
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 1
Example 2: Abandoning a transaction
127.0.0.1:6379> Set AAA 1
Ok
127.0.0.1:6379> Multi
Ok
127.0.0.1:6379> incr AAA
QUEUED
127.0.0.1:6379> Discard
Ok
127.0.0.1:6379> Get AAA
"1"
Example 3:watch lock mechanism (below, if the key being monitored is modified before exec, the transaction fails)
127.0.0.1:6379> Watch AAA
Ok
127.0.0.1:6379> Set AAA 100
Ok
127.0.0.1:6379> Multi
Ok
127.0.0.1:6379> Set AAA 200
QUEUED
127.0.0.1:6379> exec
(nil)
127.0.0.1:6379> Get AAA
"100"
Example 4:redis ignores the failed command or the wrong command
127.0.0.1:6379> Multi
Ok
127.0.0.1:6379> INCR b
QUEUED
127.0.0.1:6379> Set C 1 2
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (Error) ERR syntax error
127.0.0.1:6379> Get B
"1"
127.0.0.1:6379> get C
(nil)
As seen above, Redis is not supported for rollback (rollback) in order to be efficient and fast, but provides a script implementation transaction
。
Two. Using Lua scripts to implement transactions
Redis can invoke the LUA parser to run the script, Redis will ensure that the script runs atomically, and the execution of multiple commands can reduce network overhead, but it's not a good idea to execute a long run of scripts.
The eval command is used to execute the LUA script, and the Redis.call () function is used to invoke the Redis command. (see Redis document for details)
Examples of 1:eval and Redis.call use
127.0.0.1:6379> eval "return Redis.call (' Set ', keys[1], ' Bar ')" 1 foo
Ok
127.0.0.1:6379> get foo
"Bar"