/**
* @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);
}
}
}
redis分布式锁工具类
最新推荐文章于 2024-02-06 17:42:15 发布
本文介绍了一个基于Redis实现的分布式锁服务,包括获取锁、释放锁等核心功能,使用Jedis客户端进行操作,确保了在分布式环境下的资源同步与互斥访问。
2万+

被折叠的 条评论
为什么被折叠?



