配置
singleServerConfig:
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
reconnectionTimeout: 3000
failedAttempts: 3
subscriptionsPerConnection: 5
clientName: null
address: "redis://IP:PORT"
database: 0
password: gg123456g
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 32
connectionPoolSize: 64
dnsMonitoring: false
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
transportMode : "NIO"
@Configuration
public class RedissionConfig {
@Bean(destroyMethod = "shutdown")
RedissonClient redisson() throws Exception {
RedissonClient redisson = Redisson.create(
Config.fromYAML(new ClassPathResource("redisson.yml").getInputStream()));
return redisson;
}
}
自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Rlock {
String localKey() default "redisLockAnnotation::";
long waitTime() default 5;
long leaseTime() default 10;
TimeUnit timeUnit() default TimeUnit.SECONDS;
}
自定义切面实现
@Aspect
@Component
@Slf4j
public class RlockAspect {
@Autowired
private RedissonClient redissonClient;
@Pointcut("@annotation(com.boss.xtrain.core.db.redis.annotation.Rlock)")
public void RlockAspect() { }
@Around("RlockAspect()")
public Object arround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object object = null;
RLock lock = null;
try {
Rlock rlockInfo = getRlockInfo(proceedingJoinPoint);
lock = redissonClient.getLock(getLocalKey(proceedingJoinPoint, rlockInfo));
if (lock != null) {
final boolean status = lock.tryLock(rlockInfo.waitTime(), rlockInfo.leaseTime(), rlockInfo.timeUnit());
if (status) {
object = proceedingJoinPoint.proceed();
}else{
throw new BusinessException(ExceptionMsg.REDISSION_HAS_BEAN_USED, ExceptionMsg.REDISSION_HAS_BEAN_USED_MSG);
}
}
} finally {
if (lock != null && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
return object;
}
public Rlock getRlockInfo(ProceedingJoinPoint proceedingJoinPoint) {
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
return methodSignature.getMethod().getAnnotation(Rlock.class);
}
public String getLocalKey(ProceedingJoinPoint proceedingJoinPoint, Rlock rlockInfo) {
StringBuilder localKey = new StringBuilder();
final Object[] args = proceedingJoinPoint.getArgs();
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
String methodName = methodSignature.getMethod().getName();
localKey.append(rlockInfo.localKey()).append(methodName);
return localKey.toString();
}
}
使用
@Rlock(localKey = "redisLockAnnotation", waitTime = 3, leaseTime = 3, timeUnit = TimeUnit.SECONDS)
public void redisLockAnnotation() {
try {
log.info("thread sleep start ");
Thread.sleep(100000);
log.info("thread sleep end ");
} catch (Exception e) {
e.printStackTrace();
}
}