【问题标题】:Ensuring two redis commands are atomic if the second comman如果第二个命令确保两个 redis 命令是原子的
【发布时间】:2014-02-02 06:47:04
【问题描述】:

使用 node_redis 客户端,我怎样才能使两个命令执行,以便当第二个命令依赖于第一个命令的结果时它们将自动执行。

这是我的想法的一个例子。

client.multi([
    ["hget", orgId, topicId]
]).exec(function (err, sessions) {
    sessions = JSON.parse(sessions);
    if (sessions === undefined) {
        sessions = [sessionId];
    }
    else {
        sessions.push(sessionId)
    }
    client.hset(orgId, topicId, JSON.stringify(sessions)]);
});

如果新值同时在两个地方运行,有人可以确认不会出现写回新值的竞争条件。

【问题讨论】:

    标签: node.js node-redis


    【解决方案1】:

    正确的答案是“观察”价值。确保每个查询都有自己的连接并处理并发错误的可能性也很重要。

    var atomicReadWriteOperationRecursive = function (hashKey, valueKey, count) {
        var client = redis.createClient();
        client.watch(hashKey, valueKey);
        client.hget(hashKey, valueKey, function (err, response) {
                client.multi()
                    .hset(orgId, topicId, newValue);
                    .exec(function (err) {
                        client.close();
                        if (err && count < 3) {
                            atomicReadWriteOperationRecursive(hashKey, valueKey, count++);  
                        }
                    });
            });
    }
    

    请看这里https://github.com/mranney/node_redis/issues/545

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      相关资源
      最近更新 更多