com.gitee.fufu669.aspect.LockWithCacheAop Maven / Gradle / Ivy
package com.gitee.fufu669.aspect;
import com.gitee.fufu669.common.CacheKeyCommon;
import com.gitee.fufu669.config.exception.CacheServerErrorCode;
import com.gitee.fufu669.config.exception.CacheServerException;
import com.gitee.fufu669.service.CacheService;
import com.gitee.fufu669.utils.CacheAopUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gitee.fufu669.utils.CacheRedisKeyUtil;
import java.lang.reflect.Method;
/**
* @author wangfupeng on 2017-5-6.
*/
@Aspect
@Component
@SuppressWarnings("rawtypes")
/** @author wangfupeng */
public class LockWithCacheAop {
public static final Logger logger = LoggerFactory.getLogger(LockWithCacheAop.class);
@Autowired
private CacheService cacheService;
@Around("@annotation(com.gitee.fufu669.aspect.LockWithCache)")
public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
/* 获取注解里面的value*/
String methodName = null;
int expireSeconds = CacheKeyCommon.CACHESERVICE_REDIS_LOCK_DEFAULT_EXPIRED_SECONDS;
String description = "";
try {
String targetName = proceedingJoinPoint.getTarget().getClass().getName();
methodName = proceedingJoinPoint.getSignature().getName();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
expireSeconds = method.getAnnotation(LockWithCache.class).expireSeconds();
description = method.getAnnotation(LockWithCache.class).description();
break;
}
}
} catch (Exception e) {
logger.info(e.toString());
}
/* 拦截的方法参数名*/
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
String lockKey = CacheRedisKeyUtil.getLockWithRedisAopLockKeyRedisKey(CacheAopUtil.getCacheKey(proceedingJoinPoint));
if (cacheService.lock(lockKey, expireSeconds)) {
logger.info("%%%%%%LockWithCacheAop:aroundMethod:lockKey:" + lockKey + ":expireSeconds:" + expireSeconds + ":lock:success:description:" + description + "%%%%%%");
try {
Object object = proceedingJoinPoint.proceed();
return object;
} catch (Throwable e) {
logger.info(e.getMessage(), e);
throw e;
} finally {
logger.info("%%%%%%LockWithCacheAop:aroundMethod:lockKey:" + lockKey + ":expireSeconds:" + expireSeconds + ":unlock:success:description:" + description + "%%%%%%");
cacheService.unlock(lockKey);
}
} else {
if (description == null || description.equals("")) {
description = "";
}
throw new CacheServerException(CacheServerErrorCode.LOCKWITHREDIS_LOCK_FAILED, description);
}
}
}