redis 事务基础知识及watch乐观锁
事务初识
为了确保连续多个操作的原子性,一个成熟的数据库通常都会有事务支持。事务的原子性是指要么事务全部成功,要么全部失败。

redis事务
redis事务是一次可以执行多个命令,它的本质是一组命令的集合。
事务执行的过程中会按照顺序执行队列中的命令。其它客户端提交的命令请求会等到事务执行完毕再执行。【redis是单线程】
redis事务命令入队流程图

redis基本命令使用
Redis 事务命令分别是 multi/exec/discard。multi :事务的开始,exec 指:事务的执行,discard :事务的丢弃
语法:
multi
redis命令
redis命令
exec [discard]

事务块内所有命令的返回值,按命令执行的先后顺序排列。
QUEUED和 OK 表示指令已经被服务器缓存到队列里

redis事务与关系型数据库事务区别
1、Redis 的事务根本不能算「原子性」,而仅仅是满足了事务的「隔离性」,隔离性中的串行化——当前执行的事务有着不被其它事务打断的权利。

redis事务在遇到指令执行失败后,后面的指令还继续执行。
redis乐观锁
watch监控
语法:
WATCH key [key …]
Redis Watch 命令用于监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断



exec 在2的后面执行,结论:用watch监控key被修改,事务全部回滚(包含set name li)
注意事项:Redis 禁止在 multi 和 exec 之间执行 watch 指令,而必须在 multi 之前做好盯住关键变量,否则会出错。
redis watch 事务执行过程

UNWATCH
取消 WATCH 命令对所有 key 的监视。
如果在执行 WATCH 命令之后, EXEC 命令或 DISCARD 命令先被执行了的话,那么就不需要再执行 UNWATCH 了。
因为 EXEC 命令会执行事务,因此 WATCH 命令的效果已经产生了;而 DISCARD 命令在取消事务的同时也会取消所有对 key 的监视,因此这两个命令执行之后,就没有必要执行 UNWATCH 了。

思考
为什么 Redis 的事务不能支持回滚?
1、实际开发中,Redis错误一般不会出现在生产环境中,且Redis错误只会是传递了错误的参数类型,而这中错误会在开发环境中就被发现现。
2、由于Redis内部功能简化,确保更快的运行速度,所有不需要回滚。
官方文档:
Why Redis does not support roll backs?
If you have a relational databases background, the fact that Redis commands can fail during a transaction, but still Redis will execute the rest of the transaction instead of rolling back, may look odd to you.
However there are good opinions for this behavior:
- Redis commands can fail only if called with a wrong syntax (and the problem is not detectable during the command queueing), or against keys holding the wrong data type: this means that in practical terms a failing command is the result of a programming errors, and a kind of error that is very likely to be detected during development, and not in production.
- Redis is internally simplified and faster because it does not need the ability to roll back.
An argument against Redis point of view is that bugs happen, however it should be noted that in general the roll back does not save you from programming errors. For instance if a query increments a key by 2 instead of 1, or increments the wrong key, there is no way for a rollback mechanism to help. Given that no one can save the programmer from his or her errors, and that the kind of errors required for a Redis command to fail are unlikely to enter in production, we selected the simpler and faster approach of not supporting roll backs on errors.

浙公网安备 33010602011771号