Redis - Using Incr value in a transaction

前端 未结 1 726
北恋
北恋 2021-02-06 10:51

Is it possible to use multi.incr(value) with multi.hmset?

I mean:

var name = \'Josh\';
var multi = client.multi();
multi.incr(\         


        
相关标签:
1条回答
  • 2021-02-06 11:36

    The accepted answer above is unnecessarily complicated. You do not need to use a multi or watch in this circumstance. INCR is already atomic, and is designed for this exact scenario. Edit: Thanks to Itamar Haber & robe007 for getting the accepted answer changed. :)

    You can simply do this:

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

    By doing the above, INCR automatically locks the "id" key, increments it for you, unlocks it, and returns it to you. Thus, there is no way for anyone to get a duplicate user id using the code above. It also has the benefit of never really being able to fail, unlike WATCH/GET, where you'd have to check for failures and run your queries again if they failed.

    0 讨论(0)
提交回复
热议问题