private static final Long LOCK_SUCCESS = 1L;
private static final String TRY_LOCK_SCRIPT = "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 static final String RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

public Boolean tryLock(String lockKey, String identify, long expireTime) {
   try {
        RedisScript<String> redisScript = new DefaultRedisScript<>(TRY_LOCK_SCRIPT, String.class);
        Object result = redisStringTemplate.execute(redisScript, Collections.singletonList(lockKey), identify, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return Boolean.TRUE;
        }
    } catch (Exception e) {
        log.error("获取锁失败,lockKey=[{}], identify=[{}]", lockKey, identify, e);
    }
    return Boolean.FALSE;
}

public Boolean releaseLock(String lockKey, String identify) {
    try {
        RedisScript<String> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_SCRIPT, String.class);
        Object result = redisStringTemplate.execute(redisScript, Collections.singletonList(lockKey), identify);
        if (LOCK_SUCCESS.equals(result)) {
            return Boolean.TRUE;
        }
    } catch (Exception e) {
        log.error("解锁失败,lockKey=[{}], identify=[{}]", lockKey, identify, e);
    }
    return Boolean.FALSE;
}
Logo

更多推荐