Public class Redistool {
private static final String lock_success = "OK";
private static final String set_if_not_exist = "NX";
private static final String Set_with_expire_time = "PX"; /** * Attempt to acquire distributed lock * @param jedis redis client * @param lockkey lock * @param requestid Request identification * @param expiretime extended time * @return
Whether to get success/public static Boolean Trygetdistributedlock (Jedis Jedis, String Lockkey, string requestid, int expiretime) {
String result = Jedis.set (Lockkey, RequestID, Set_if_not_exist, Set_with_expire_time, expiretime);
if (lock_success.equals (Result)) {return true;
return false;
private static final Long release_success = 1L; /** * Release Distributed lock * @param jedis redis client * @param lockkey lock * @param requestid Request Identity * @return whether to release success/public static Bo Olean Releasedistributedlock (Jedis Jedis, String Lockkey, String RequestID) {String script = ' If Redis.call (' Get ', K
EYS[1] = = Argv[1] then return Redis.call (' del ', Keys[1]) else return 0 "; Object result = Jedis.eval (sCript, Collections.singletonlist (Lockkey), Collections.singletonlist (RequestID));
if (release_success.equals (Result)) {return true;
return false;
}
}
As you can see, we only need two lines of code to unlock it. The first line of code, we wrote a simple LUA scripting code, the last time I saw this programming language in "hackers and painters", did not think this time actually used.
In the second line of code, we pass the LUA code to the Jedis.eval () method, and assign the parameter keys[1 to lockkey,argv[1] to the RequestID. The eval () method is to deliver the LUA code to the Redis server for execution.
So what is the function of this LUA code? In fact, it is very simple, first get the value of the lock corresponding to check whether and RequestID equal,
If equal, remove the lock (unlock). So why use the Lua language to implement it. Because you want to make sure that the above operation is atomic. You can read "Unlock code-error Example 2" For what the problem is with non atomicity.
So why does the eval () method ensure atomicity, derived from Redis attributes:
Simply put, when the eval command executes the LUA code, the LUA code is executed as a command, and Redis executes other commands until the eval command completes.