Springboot+分布式锁Redisson注解封装
package com.walker.redisson.aspect;
import cn.hutool.core.util.StrUtil;
import com.walker.redisson.annotation.RedissonLock;
import com.walker.redisson.service.RedisLockService;
import com.walker.redisson.utils.SpElUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Slf4j
@Component
@Aspect
public class RedissonLockAspect {
@Autowired
private RedisLockService redisLockService;
// 也可以直接注入切点的
@Around(value = "@annotation()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取方法
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
// 获取注解
RedissonLock annotation = method.getAnnotation(RedissonLock.class);
// 获取key的前缀 如果没有设置的话,获取获取全限定类名+方法名
String prefix=StrUtil.isEmpty(annotation.prefixKey())? SpElUtils.getMethodKey(method):annotation.prefixKey();
StringBuilder keySB = new StringBuilder();
keySB.append(prefix);
// 如果后缀key非空
String suffixKey = annotation.suffixKey();
if(StrUtil.isNotEmpty(suffixKey)){
// 如果包含# 则进行El表达式解析
if(suffixKey.contains("#")){
String[] split = suffixKey.split(annotation.delimiter());
for (String spEl : split) {
// 解析El表达式
String keyItem = SpElUtils.parseSpEl(method, joinPoint.getArgs(), spEl);
if(StrUtil.isEmpty(keyItem)) continue;
keySB.append(annotation.delimiter()+keyItem);
}
}else{
keySB.append(annotation.delimiter()+suffixKey);
}
}
// 锁+逻辑处理
return redisLockService.executeWithLockThrows(keySB.toString(),annotation.waitTime(),annotation.timeUnit(),joinPoint::proceed);
}
}