Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top