springboot整合redis 都是老套玩法了,不再赘述记录
一、创建自定义注解,此自定义注解适用范围设定为method
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TaskRedisLock {
String appKey() default "appName";
String value() default "";
long maxLockTime() default 300;
}
二、利用spring切面方法执行前后进行redis加锁判断和执行后移除锁
@Aspect
@Component
@Slf4j
public class AnnotationAspect {
@Autowired
private RedisTemplate redisTemplate;
@Around("@annotation(com.systerm.TaskRedisLock)")
public Object TaskLockExistQuery(ProceedingJoinPoint proceedingJoinPoint) {
Method m=getMethod(proceedingJoinPoint,TaskRedisLock.class);
TaskRedisLock taskRedisLock=m.getAnnotation(TaskRedisLock.class);
String redisMethodKey = getRedisSecondKey(proceedingJoinPoint);
boolean redisLock = redisTemplate.setIfAbsent(taskRedisLock.appKey().concat(-).concat(redisMethodKey)
,taskRedisLock.value(),taskRedisLock.maxLockTime()*1000);
if (!redisLock) {
String redisKey = String.format("redisKey:%s-%s is exist",taskRedisLock.appKey(),redisMethodKey )
log.warn(redisKey);
throw new RuntimeException(redisKey );
}
Object returnObj=null;
try{
returnObj= proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
} catch(Exception e){
log.error("task lock run:[exception]",e);
} catch(Throwable e){
log.error("task lock run:[throwable]",e);
}
finally{
MethodSignature ms = (MethodSignature)proceedingJoinPoint.getSignature();
log.info("[success] run success: task check method:" + ms.getMethod().getName() +
" class:" + proceedingJoinPoint.getSignature().getDeclaringTypeName()+" ip:"+ IpUtil.getIp(), true);
redisTemplate.delete(taskRedisLock.appKey().concat(-).concat(redisMethodKey));
}
return returnObj;
}
private String getRedisSecondKey(ProceedingJoinPoint proceedingJoinPoint){
MethodSignature ms = (MethodSignature)proceedingJoinPoint.getSignature();
StringBuffer key=new StringBuffer();
key.append(ms.getDeclaringTypeName());
key.append("-");
key.append(ms.getMethod().getName());
if(proceedingJoinPoint.getArgs()!=null){
for(Object obj:proceedingJoinPoint.getArgs()){
if(obj!=null && !(obj instanceof Date)){
String str=obj.toString().replace(" ", "-");
key.append("-");
key.append(str);
}
}
}
return key.toString();
}
private Method getMethod(ProceedingJoinPoint proceedingJoinPoint, Class<? extends Annotation> clazz){
MethodSignature ms = (MethodSignature) proceedingJoinPoint.getSignature();
if (ms.getMethod().isAnnotationPresent(clazz)){
return ms.getMethod();
}
Method m = ms.getMethod();
try{
Method m1 = proceedingJoinPoint.getTarget().getClass().getMethod(m.getName(), m.getParameterTypes());
if (m1.isAnnotationPresent(clazz)){
return m1;
}
}catch (Exception e){
log.error("AnnotationAspect get annotation aspect method error",e);
}
throw new RuntimeException("adaptation annotations not found.");
}
}
三、实际业务method使用
@Service
public class doServiceManagerImpl implements doServiceManager{
@TaskRedisLock(appKey = "appName",value = "1",maxLockTime = 600)
public void process(){
}
}