redis之事务

redis之事务

MULTI, EXEC, DISCARD and WATCH are the foundation of transactions in Redis

A transaction in redis consists of a block of commands placed between MULTI and EXEC (or DISCARD for rollback). Once a MULTI has been encountered, the commands on that connection are not executed - they are queued (and the caller gets the reply QUEUED to each). When an EXEC is encountered, they are all applied in a single unit (i.e. without other connections getting time between operations). If a DISCARD is seen instead of a EXEC, everything is thrown away. Because the commands inside the transaction are queued, you can’t make decisions inside the transaction.

WATCH {key} tells Redis that we are interested in the specified key for the purposes of the transaction. Redis will automatically keep track of this key, and any changes will essentially doom our transaction to rollback - EXEC does the same as DISCARD (the caller can detect this and retry from the start). So what you can do is: WATCH a key, check data from that key in the normal way, then MULTI/EXEC your changes. If, when you check the data, you discover that you don’t actually need the transaction, you can use UNWATCH to forget all the watched keys. Note that watched keys are also reset during EXEC and DISCARD. So at the Redis layer, this is conceptually:

WATCH {custKey}
HEXISTS {custKey} "UniqueId"
(check the reply, then either:)
MULTI
HSET {custKey} "UniqueId" {newId}
EXEC
(or, if we find there was already an unique-id:)
UNWATCH

区别于关系数据库的transaction。

Redis事务没有隔离级别的概念:

  批量操作在发送 EXEC 命令前被放入队列缓存,并不会被实际执行,也就不存在事务内的查询要看到事务里的更新,事务外查询不能看到。

Redis不保证原子性:

  Redis中,单条命令是原子性执行的,但事务不保证原子性,且没有回滚。事务中任意命令执行失败,其余的命令仍会被执行。

watch指令类似于乐观锁,在事务提交时,如果watch监控的多个KEY中任何KEY的值已经被其他客户端更改,则使用EXEC执行事务时,事务队列将不会被执行



https://redis.io/topics/transactions

https://redis.io/topics/transactions