Redis提供了一个乐观锁的事务机制,WATCH-MULTI-EXEC。其作用非常类似于DB的check-and-set(CAS)乐观锁实现:

boolean success = false;
do{
	y = exec_sql("elect a from xxx");
	x = y + n;
	success = exec_sql("udpate a = x where a = y");
} while(!success)

同样的,在Redis中,我们可以这样子实现:

boolean success = false;
do{
	redis.watch('a');
	y = redis.get('a');
	redis.multi();
	redis.set('a', y + n); // QUEUED
	success = redis.exec(); // failure if a has changed and was watched.
}while(!success)

With a WATCH clause, the commands between MULTI and EXEC are executed only if the value has not changed.

值得注意的是Redis并不支持回滚,虽然它有一个看起来像是回滚的命令:DISCARD。但是这个命令的作用是丢弃那些还没有执行(queued commands)的命令,而不是已经执行的命令。

TIPS 另一种事务方式是使用脚本。

参考文章

  1. Transactions

本文由 arganzheng 创作,采用 CC BY 4.0 许可协议。在保留原文作者、署名以及完整原文链接(https://arganzheng.life/redis-transaction.html)的前提下,欢迎各种形式的转载、翻译或商业引用。


COMMENTS

评论存放在 GitHub Discussions, 用 GitHub 账号登录即可发表,支持 Markdown。 想针对正文某句话说?选中那段文字,点浮出的「评论」即可划线评论;觉得哪里写错了,发表时勾上「同时提交 Issue」。 有人回复你时 GitHub 会按你的通知设置发邮件,不用守在这里。

×