Redis - 在事务中使用 Incr 值

Redis - Using Incr value in a transaction

是否可以将 multi.incr(value)multi.hmset 一起使用?

我的意思是:

var name = 'Josh';
var multi = client.multi();
multi.incr('id'); // incr => 1
multi.hmset('user:' + <need incr value here>, 'username', name);
// I want multi.hmset('user:1', 'username', 'Josh');
multi.exec(function(err,data){ .. });

我的objective是自增'id',然后在事务中设置为用户id。我读过,我需要做 client.watch('id'),但我不明白如何使用它。

PD:拜托,post 你用代码回答是最好的方法:)

上面接受的答案不必要地复杂。在这种情况下,您不需要使用 multi 或 watch。 INCR 已经是原子的,专为这种情况而设计。 编辑:感谢 Itamar Haber 和 robe007 更改了已接受的答案。 :)

您可以简单地这样做:

var name = 'Josh';
client.incr('id', function(err, id) {
    client.hmset('user:' + id, 'username', name);
});

通过执行上述操作,INCR 会自动锁定 "id" 键,为您递增,解锁,然后 returns 给您。因此,任何人都无法使用上面的代码获得重复的用户 ID。它还具有永远不会失败的好处,这与 WATCH/GET 不同,在后者中您必须检查失败并在失败时再次 运行 您的查询。