/**
* @ClassName RedisLock
* @Description redis分布式锁服务
* @Author zyy
*/
@Component
public class RedisLockService {
private static final String LOCK_SUCCESS = "OK";
private static final Long UNLOCK_SUCCESS = 1L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "EX";
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";
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 获取锁
* @param lockKey
* @param value
* @param expireTime:单位-秒
* @return
*/
public boolean getLock(String lockKey, String value, int expireTime){
return stringRedisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
Jedis jedis = (Jedis) redisConnection.getNativeConnection();
String result = jedis.set(lockKey, value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
});
}
/**
* 释放锁
* @param lockKey
* @param value
* @return
*/
public boolean unLock(String lockKey, String value) {
return stringRedisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
Jedis jedis = (Jedis) redisConnection.getNativeConnection();
Long result = (Long) jedis.eval(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey),
Collections.singletonList(value));
if (UNLOCK_SUCCESS.equals(result)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
});
}
/**
* 获取分布式锁
* @param lockKey
*/
public boolean tryLock(String lockKey, String lockValue){
return this.getLock(lockKey, lockValue, Constants.THIRTY_SECONDS);
}
/**
* 获取分布式锁
* @param lockKey
* @param lockValue
* @param lockTime
* @return
*/
public boolean tryLock(String lockKey, String lockValue, int lockTime){
return this.getLock(lockKey, lockValue, lockTime);
}
/**
* 解锁
* @param lockKey
*/
public void removeLock(String lockKey, String lockValue){
try {
this.unLock(lockKey, lockValue);
}catch (Exception e){
throw new FinanceFastFailException("解锁失败 lockKey" + lockKey);
}
}
}