문제

Using the node_redis client, how can I make two commands execute such that they will be performed atomically when the second command relies on the result of the first.

Here is an example of what I am thinking.

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)]);
});

Can someone confirm there would not be a race condition to write back the new value if this ran simultaneously in two places.

도움이 되었습니까?

해결책

The right answer is to "watch" the value. It is also important to make sure each query has its own connection and handles the possibility of a concurrency error.

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++);  
                    }
                });
        });
}

See here https://github.com/mranney/node_redis/issues/545.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top