暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

与redis相关的分布式锁简单实现

Java技术学习笔记 2020-12-12
532

基于redisTemplate

public class RedissonDistributedLock {
private static final Logger LOGGER = LoggerFactory.getLogger(RedissonDistributedLock.class);


private RedisTemplate<Serializable, Serializable> redisTemplate;


public void setRedisTemplate(RedisTemplate<Serializable, Serializable> redisTemplate) {
this.redisTemplate = redisTemplate;
}


public JsonResult synchronize(String lockName, LockSupplier<JsonResult> lockSupplier) {
String key = "LOCK" + lockName;
boolean result = tryLock(key, 1, 5000L, TimeUnit.MILLISECONDS);
if (!result) {
// 超时时间
Long expire = redisTemplate.getExpire(key);


if (expire.equals(-1L)){
// 补充过期时间
redisTemplate.expire(key, 5000L, TimeUnit.MILLISECONDS);
}
LOGGER.info(key + "请勿重复操作");
return new JsonResult(false, "请勿重复操作");
}
try {
return lockSupplier.run();
} catch (Exception e){
LOGGER.error("锁lockName=" + lockName + "异常", e);
throw new MyException(e.getMessage());
}finally {
deleteLock(key);
}
}


/**
     * 创建锁 -- 不支持过期时间的版本
* @param lockKey
* @param value
* @param releaseTime
* @return
*/
    public boolean tryLock(String lockKey, int value, long releaseTime, TimeUnit timeUnit) {
Boolean store = redisTemplate.opsForValue().setIfAbsent(lockKey,value);
if(null != store && store){
redisTemplate.expire(lockKey,releaseTime, timeUnit);
return true;
}
LOGGER.error("redis加锁时,setIfAbsent返回值异常,返回值是" + store);
return false;
}

/**
     * 创建锁 -- 支持过期时间设置
* @param lockKey
* @param value
* @param releaseTime
* @return
*/
public boolean tryLock2(String lockKey, int value, long releaseTime, TimeUnit timeUnit) {
Boolean store = redisTemplate.opsForValue().setIfAbsent(lockKey,value,releaseTime,timeUnit);
if(store){
return true;
}
return false;
}


/**
* 删除锁
* @param key
*/
public void deleteLock(String key) {
redisTemplate.delete(key);
}
}

基于redisson

<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
</dependency>
@Bean
public RedissonClient redissonClient() {
return Redisson.create(this.config());
}


@Bean
public RedissonDistributedLock redissonDistributedLock(RedissonClient redissonClient) {
return new RedissonDistributedLock(redissonClient);
}
public class RedissonDistributedLock {


private RedissonClient redissonClient;


public RedissonDistributedLock(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}


public Object synchronize(String lockName, Function<String, Object> function) throws Exception {
String key = "LOCK" + lockName;
RLock rlock = this.redissonClient.getLock(key);
boolean lock = false;


Object result;
try {
            // tryLock(long waitTime, long leaseTime, TimeUnit unit)
lock = rlock.tryLock(5000L, 10000L, TimeUnit.MILLISECONDS);
if (!lock) {
log.error("get lock is null");
throw new RuntimeException("null");
}
// 执行代码
result = function.apply(lockName);
} finally {
if (null != rlock && lock && rlock.isLocked()) {
rlock.unlock();
}
}
return result;
}
}

执行部分

public JsonResult synchronize() throws Exception {
try {
// key
String key = "唯一key";
// 执行
Object synchronize = redissonDistributedLock.synchronize(key, (t) -> {
// 执行代码部分
return new JsonResult();
});
if (synchronize instanceof JsonResult){
return (JsonResult) synchronize;
}
return new JsonResult();
} catch (Exception e){
e.printStackTrace();
return new JsonResult(false, e.getMessage());
}
}
文章转载自Java技术学习笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论