摘自:https://www.zhaochao.top/article/179,更多开发技术请访问 https://www.zhaochao.top
首先编写@Cached注解
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Cache {
// 默认缓存时间 单位毫秒,默认2分钟,切勿随意修改默认值
long expire() default 120000L;
// 缓存时间默认添加的随机时间 默认10秒
int randomMillis() default 10000;
@AliasFor("key")
String value() default "";
@AliasFor("value")
String key() default "";
}
编写核心Aop缓存任务
package cn...core.infrastructure.aspect.cache;
import cn...core.infrastructure.annotate.cache.Cache;
import cn...core.infrastructure.entity.GeneralResult;
import cn...core.infrastructure.enums.ErrorEnums;
import cn...core.infrastructure.enums.LogEnums;
import cn...core.infrastructure.util.RedisUtil;
import cn...core.infrastructure.util.XLoggerUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author zhaochao53
*/
@Aspect
@Component
public class RedisCacheAspect {
/**
* 方法全路径对应的返回值类型Type
*/
private static ConcurrentHashMap<String, Type> methodFullNameWithType = new ConcurrentHashMap<>(128);
private ExpressionParser parser = new SpelExpressionParser();
private LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
@Autowired
private RedisUtil redis;
@Pointcut("@annotation(cn...core.infrastructure.annotate.cache.Cache)")
public void cachedAspect() {
}
@Around(value = "cachedAspect()")
public Object cache(ProceedingJoinPoint pjp) throws Throwable {
// 获取方法名
Signature signature = pjp.getSignature();
String methodName = signature.getName();
Object[] args = pjp.getArgs();
// 获取方法的注解
Method targetMethod = ((MethodSignature) signature).getMethod();
Method realMethod = pjp.getTarget().getClass().getDeclaredMethod(methodName, targetMethod.getParameterTypes());
Map<String, Object> params = new HashMap<>(1 << 3);
params.put("methodName", methodName);
params.put("fullName", targetMethod.getDeclaringClass().getName());
params.put("simpleName", targetMethod.getDeclaringClass().getSimpleName());
String prefix = targetMethod.getDeclaringClass().getSimpleName() + "::" + methodName;
Cache cached = targetMethod.getAnnotation(Cache.class);
String[] paramList = discoverer.getParameterNames(targetMethod);
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariables(params);
if (paramList != null) {
for (int len = 0; len < paramList.length; len++) {
context.setVariable(paramList[len], args[len]);
}
}
if (args != null) {
for (int len = 0; len < args.length; len++) {
context.setVariable("arg" + len, args[len]);
}
}
String key = prefix + ":";
if (StringUtils.isNotBlank(cached.key())) {
Expression expression = parser.parseExpression(cached.key());
key += expression.getValue(context, String.class);
} else if (args != null && args.length > 0) {
key += StringUtils.join(args, ".");
}
String str = redis.get(key);
if (StringUtils.isNotBlank(str)) {
try {
return getFromCache(realMethod, prefix, str, pjp, args, cached, key);
} catch (Throwable t) {
XLoggerUtil.sysErrLog("获取结果并设置缓存失败", t);
return null;
}
} else {
return processAndCache(pjp, args, cached, key);
}
}
/**
* JSON字符串转换为对象
*
* @param realMethod
* @param methodFullName
* @param str
* @return
*/
private Object getFromCache(Method realMethod, String methodFullName, String str, ProceedingJoinPoint pjp, Object[] args, Cache cached,
String key) throws Throwable {
Object proceed;
try {
Parameter[] parameters = realMethod.getParameters();
if (parameters != null && parameters.length > 0) {
StringBuilder params = new StringBuilder(methodFullName);
for (Parameter parameter : parameters) {
params.append(".").append(parameter.getName());
}
methodFullName = params.toString();
}
Type type = getType(methodFullName, realMethod);
if (type == null) {
XLoggerUtil.log("未获取到方法全路径对应Type ==> methodFullName = {}", methodFullName);
return GeneralResult.warnMessage("缓存处理出错");
}
proceed = JSON.parseObject(str, type);
} catch (Exception e) {
XLoggerUtil.sysErrLog("JSON字符串转换为对象失败 json = {}", e, str);
return processAndCache(pjp, args, cached, key);
}
return proceed;
}
private Type getType(String methodFullName, Method realMethod) {
if (StringUtils.isBlank(methodFullName)) {
return null;
}
try {
Type type = methodFullNameWithType.get(methodFullName);
if (type == null) {
type = realMethod.getGenericReturnType();
methodFullNameWithType.put(methodFullName, type);
XLoggerUtil.debug("设置方法全路径对应Type ==> methodFullName = {}, methodFullNameWithType.size = {}", methodFullName, methodFullNameWithType.size());
}
return type;
} catch (Exception e) {
XLoggerUtil.sysErrLog("获取方法全路径对应Type出错 ==> methodFullName = {}", e, methodFullName);
}
return null;
}
/**
* 执行业务方法之后缓存结果
*
* @param pjp
* @param args
* @param cached
* @param key
* @return
* @throws Throwable
*/
private Object processAndCache(ProceedingJoinPoint pjp, Object[] args, Cache cached, String key) throws Throwable {
Object proceed;
proceed = pjp.proceed(args);
try {
if (proceed != null) {
long expire = cached.expire();
int i = cached.randomMillis();
expire = i > 0 ? (expire + new Random().nextInt(i)) : expire;
if (proceed instanceof GeneralResult) {
// 如果是GeneralResult 判断是否成功
GeneralResult result = (GeneralResult) proceed;
if (!result.isSuccess()) {
// 不成功就缓存1~2秒即可
expire = 1000 + new Random().nextInt(1000);
}
}
redis.set(key, JSON.toJSONString(proceed), expire);
}
} catch (Exception e) {
// redis 异常
XLoggerUtil.errorLog(LogEnums.LogAttr.SQL,"缓存AOP", ErrorEnums.Redis.operateError.getCode(),"设置缓存出错 key = {}", key, e);
}
return proceed;
}
}
测试使用
@Cache(key = "'XXXXXXX:bm:version:' + #schoolId", expire = 10 * 60 * 1000L)
@Override
public GeneralResult<String> getVersionBySchoolId(Integer schoolId) {
if (schoolId == null || schoolId < 0) {
XLoggerUtil.paramErrLog("学校ID不合法", null);
return GeneralResult.invalidParam("学校ID不合法");
}
Map<String, String> paramsMap = new HashMap<>(2);
paramsMap.put("schoolId", schoolId.toString());
return apiHandle.genDoGetInfo(bmProperty.getApiUrl(), "获取学校报名系统版本", bmProperty.getBmSysVersionPath(), paramsMap, String.class);
}
这个是出初始版本,可以结合Gson进行优化等等!