新增自定义redis锁工具类

This commit is contained in:
gaoqr
2024-11-11 10:19:35 +08:00
parent 11dad7c369
commit 09f28fa6e5
5 changed files with 97 additions and 1 deletions
@@ -2,6 +2,8 @@ package com.cf.imes.framework.redis.config;
import cn.hutool.core.text.StrPool;
import com.cf.imes.framework.redis.core.TimeoutRedisCacheManager;
import com.cf.imes.framework.redis.util.RedisLockUtil;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -79,4 +81,8 @@ public class ChenfengCacheAutoConfiguration {
return new TimeoutRedisCacheManager(cacheWriter, redisCacheConfiguration);
}
@Bean
public RedisLockUtil lockUtil(ChenfengCacheProperties chenfengCacheProperties, RedissonClient client) {
return new RedisLockUtil(chenfengCacheProperties, client);
}
}
@@ -24,4 +24,15 @@ public class ChenfengCacheProperties {
*/
private Integer redisScanBatchSize = REDIS_SCAN_BATCH_SIZE_DEFAULT;
/**
* 超时时间,单位:毫秒(ms)
* 默认5分钟
*/
private int lockTimeout = 300000;
/**
* 等待获取锁的时间,单位:毫秒(ms)
* 默认0.5秒
*/
private int lockWaitTime = 500;
}
@@ -0,0 +1,77 @@
package com.cf.imes.framework.redis.util;
import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.redis.config.ChenfengCacheProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;
/**
* redis锁工具类
*
* @author Gqr
* @since 2024/11/8 18:43
*/
@AllArgsConstructor
@Slf4j
public class RedisLockUtil {
private ChenfengCacheProperties chenfengCacheProperties;
private RedissonClient redissonClient;
/**
* 加锁
*
* @param key rediskey
* @return true拿到锁,反之没有做对应的业务提醒
*/
public boolean lock(String key) {
boolean getLock = false;
try {
RLock lock = redissonClient.getLock(key);
return lock.tryLock(chenfengCacheProperties.getLockWaitTime(), chenfengCacheProperties.getLockTimeout(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error("[RedisLockUtil][lock]加锁失败", e);
return getLock;
}
}
/**
* 加锁
*
* @param key rediskey
* @param timeout 锁的超时时间,传空则按照默认配置
* @param waitTime 等待获取锁的时间,传空则按照默认配置
* @return true拿到锁,反之没有做对应的业务提醒
*/
public boolean lock(String key, Integer waitTime, Integer timeout) {
boolean getLock = false;
try {
RLock lock = redissonClient.getLock(key);
int wt = ObjectUtil.isNull(waitTime) ? chenfengCacheProperties.getLockWaitTime() : waitTime;
int to = ObjectUtil.isNull(timeout) ? chenfengCacheProperties.getLockTimeout() : timeout;
return lock.tryLock(wt, to, TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error("[RedisLockUtil][lock]加锁失败", e);
return getLock;
}
}
/**
* 解锁
*
* @param key rediskey
*/
public void unlock(String key) {
try {
RLock lock = redissonClient.getLock(key);
lock.unlock();
} catch (Exception e) {
log.error("[RedisLockUtil][unlock]解锁失败", e);
}
}
}