我想用 StackExchange.Redis 做一个基本的手表。如果在事务期间更改了密钥,则会失败。
StackExchange.Redis 很好地将其抽象为“条件”api,它支持“等于”和“存在”的概念。
这真的很好,但我想做一些类似“不变”的事情。我可能会遗漏一些东西,但在这一点上我还不清楚如何做到这一点。
是否可以执行以下操作:
var transaction = redis.CreateTransaction();
transaction.AddCondition(Condition.StringUnchanged("key")); //the API here could maybe be simplified
var val = transaction.StringGet("key"); //notably, this is not async because you would have to get the result immediately - it would only work on watched keys
transaction.StringSetAsync("key", val + 1);
transaction.Execute();
甚至可能是更好的版本(可以做同样的事情):
var transaction = redis.CreateTransaction();
var val = transaction.Watch("key"); //this would return the value!
transaction.StringSetAsync("key", val + 1);
transaction.Execute();
目前,我理解这样做的唯一方法是按照以下方式做一些事情:
var val = redis.StringGet("key");
var transaction = redis.CreateTransaction();
transaction.AddCondition(Condition.StringEqual("key", val));
transaction.StringSetAsync("key", val + 1);
transaction.Execute();
从阅读 SE.Redis 代码的尝试中,我理解翻译成类似的东西(不确定这有多准确):
val = GET key
WATCH key
MULTI
val = val + 1
SET key $val
checkVal = GET key
(then if checkVal != val:) UNWATCH
(otherwise:) EXEC
我仍在学习更多关于 Redis 的知识,但我不太确定这样做有什么好处。您不希望最终结果更像这样吗?:
WATCH key
MULTI
val = GET key
val = val + 1
SET key $val
EXEC
还是 SE.Redis 的工作方式不可能做到这一点?