0

I use such code to achieve Redis distributed lock:

DefaultRedisScript<String> script = new DefaultRedisScript<>();
script.setScriptText("if not redis.call('get', KEYS[1]) then return redis.call('set', KEYS[1], ARGV[1],'ex',ARGV[2],'nx') else return false end");
String result = redisTemplate.execute(script,
            Collections.singletonList("REDIS_KEY_INDEX_LOCK"), "exists", "60");

I expect the result will be among "OK", "Nil" and "false".I checked the document, the set directive with 'NX','EX' will return "OK" or "Nil". My code's result is that the key REDIS_KEY_INDEX_LOCK is set with the value exists successfully in Redis, but the value of the Java variable result is null. redisTemplatet variable is a instance of StringRedisTemplate ,I'm use Spring-Data-Redis.

Please help me, explaining why I got an unexpected result and how to correct it.

Rick
  • 141
  • 2
  • 15

1 Answers1

0

I know the reason now after reading Spring-Data-Redis source code, the script's return type needs to be specified explicitly.

DefaultRedisScript<String> script = new DefaultRedisScript<>();
script.setScriptText("if not redis.call('get', KEYS[1]) \n" +
            "then if(redis.call('set', KEYS[1], ARGV[1],'EX',ARGV[2],'NX'))  \n" +
            "    then return \"true\";\n" +
            "    else return \"false\";\n" +
            "end\n" +
            "else return \"false\";\n" +
            "end");
script.setResultType(String.class);//need to specify return type explicitly
String result = redisTemplate.execute(script,
            Collections.singletonList("REDIS_KEY_INDEX_LOCK"),"exists","60");

return result.equals("true");
Rick
  • 141
  • 2
  • 15