1.先创建一个自定义注解需要用到@Retention 注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodCache {
int expireSeconds() default 60;
String key() default "";
boolean limitQuery() default true;
String explain() default "";
}
上述注解定义好我们可以在方法上使用
@MethodCache(expireSeconds = 1200,key = "cacheKey",explain = "列表信息")
2.定义切面进入的标准利用上述建的MethodCache注解
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.core.util.domain.Response;
import com.factory.annotation.MethodCache;
import com.factory.util.HashAlgorithms;
import com.factory.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.net.Httpcookie;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Aspect
@Order(value = 2)
@Component
public class MethodCacheAspect {
@Resource
private RedisUtil redisUtil;
//定义MethodCacheKey唯一标识,方便对Key做统一的处理
private final String METHOD_CACHE_KEY = "MethodCacheKey-";
private static Logger log = LoggerFactory.getLogger(MethodCacheAspect.class);
@Around("@annotation(methodCache)")
public Object execute(ProceedingJoinPoint proceedingJoinPoint, MethodCache methodCache) throws Throwable {
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = methodSignature.getMethod();
if(StringUtils.isNotEmpty(methodCache.explain())){
log.info("[MethodCache]加载方法{}",methodCache.explain());
}else{
log.info("[MethodCache]加载方法{}",method.getName());
}
// 解析请求参数
List
3.现在就可以使用注解了切面缓存查询了
//缓存查询
@MethodCache(expireSeconds = 1200,key = "cacheKey",explain = "列表")
@GetMapping(value = "findCacheKey")
public Response findCacheKey(@RequestParam(required = true) String channelCode,@RequestParam(required = true)String comCode) {
//上面用到@MethodCache注解 会先切面查询缓存 缓存没有查询到再进入此方法查询
}


