Redis achieve Distributed Lock 3 - Use LUA script implementation of distributed locks, atomic solve problems

    private static final Long SUCCESS = 1L;
    private static String script1 = "if redis.call('setNx',KEYS[1],ARGV[1])  then " +
            "   if redis.call('get',KEYS[1])==ARGV[1] then " +
            "      return redis.call('expire',KEYS[1],ARGV[2]) " +
            "   else " +
            "      return 0 " +
            "   end " +
            "end";
    private RedisScript<String> lockRedisScript1 = new DefaultRedisScript<>(script1, String.class);
    private static String script2 = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    private RedisScript<String> unLockRedisScript = new DefaultRedisScript<>(script2, String.class);
    /**
     * Get Lock
     *
     * @Param lockKey redis 的 key
     * Value is required @param value redis random string, to prevent the release of other lock requests
     * @Param expireTime redis expiration of key units of time (in seconds) to prevent a deadlock that causes other requests unable to perform normal business
     * @return
     */
    @Override
    public  boolean lock(String lockKey, String value, long expireTime) {
        // serialization of non-string type
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        Object result = redisTemplate.execute(lockRedisScript1, Collections.singletonList(lockKey), value, String.valueOf(expireTime));

        return SUCCESS.equals(result);

    }

    /**
     * Release the lock
     *
     * @Param lockKey redis 的 key
     * @Param value redis value ratio of value only to the same, in order to determine this request is added to the normal lock release
     * @return
     */
    @Override
    public  boolean unlock(String lockKey, String value) {
        try {
            Object result = redisTemplate.execute(unLockRedisScript, Collections.singletonList(lockKey), value);
            if (SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return false;
    }

  

Guess you like

Origin www.cnblogs.com/brant/p/12539059.html