Redis Transaction

  • A transaction in Redis consists of a block of commands.
  • MULTI, EXEC, DISCARD and WATCH are the foundation of transactions in Redis
  • All the commands in a transaction are serialized and executed sequentially.
  • It can never happen that a request issued by another client is served in the middle of the execution of a Redis transaction. This guarantees that the commands are executed as a signle isolated operation.
  • Either all of the commands or none are processed, so a Redis transaction is also atomic.
  • So if a client passed invalid command to the server in the context of a transaction then none of the operations are performed.

Multi and Exec

127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> set name kimi
QUEUED
127.0.0.1:6379(TX)> set name2 kk
QUEUED
127.0.0.1:6379(TX)> exec
1) OK
2) OK
127.0.0.1:6379> get name
"kimi"
127.0.0.1:6379> get name2
"kk"

Discard

127.0.0.1:6379> set bank1 1000
OK
127.0.0.1:6379> set bank2 2000
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> incrby bank1 100
(integer) 1100
127.0.0.1:6379> incrby bank2 100
(integer) 2100
127.0.0.1:6379(TX)> discard
OK
127.0.0.1:6379> exec
(error) ERR EXEC without MULTI
127.0.0.1:6379> get bank1
"1000"

Watch

127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> incrby bank1 100
QUEUED
127.0.0.1:6379(TX)> exec
1) (integer) 1100
127.0.0.1:6379> watch bank1
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> incrby bank1 100
QUEUED
127.0.0.1:6379(TX)> exec
1) (integer) 1200

watch之後 值被改了

127.0.0.1:6379> watch bank1
OK
127.0.0.1:6379> incrby bank1 100
(integer) 1300
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> incrby bank1 100
QUEUED
127.0.0.1:6379(TX)> exec
(nil)

Unwatch

127.0.0.1:6379> watch bank1
OK
127.0.0.1:6379> unwatch
OK
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:53

results matching ""

    No results matching ""

    results matching ""

      No results matching ""