Search code examples
javaredisjediskeydb

Redis set key, val only if val matches a previous one for concurrency


How can one do this? Using Jedis and Java.

I am working with hset right now, but does no really matter.

Does one have to send along lua code to achieve this? How is that done with Jedis?


Solution

  • Here is a Check-n-set for HSET command using LUA.

    Jedis jedis;
    String key, field, oldValueToCheck, newValueToSet;
    
    jedis.eval("if redis.call('HGET', KEYS[1], ARGV[1]) == ARGV[3]"
        + " then return redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])"
        + " else return 'NA' end", 1, key, field, newValueToSet, oldValueToCheck);