
top.doudou.common.aop.aspect.CacheBaseAspect Maven / Gradle / Ivy
package top.doudou.common.aop.aspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.annotation.Order;
import top.doudou.base.util.ServletUtils;
import top.doudou.common.aop.aspect.entity.AspectCacheDto;
import top.doudou.common.redis.RedisUtil;
import top.doudou.core.util.UrlUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import static top.doudou.common.aop.aspect.AspectUtils.getParameterStr;
/**
* @author 傻男人<[email protected]>
* @Date: 2020/8/25 14:06
* @Version: 1.0
* @Description: 请求日志的记录抽象类
* 需要使用logPrintPointCut这个方法来定义切面的切入点
*/
@Order
@Slf4j
@EnableConfigurationProperties({AspectProperties.class})
public class CacheBaseAspect {
@Autowired
private RedisUtil redisUtil;
@Autowired
private AspectProperties aspectProperties;
private static final String CACHE_PREFIX = "interface_date_cache_";
@Around("pointCut()")
public Object interfaceDateCache(ProceedingJoinPoint point) throws Throwable {
HttpServletRequest request = ServletUtils.getRequest();
String requestMethod = request.getMethod();
if(!"GET".equalsIgnoreCase(requestMethod)){
return point.proceed();
}
List cache = aspectProperties.getCache();
if(CollectionUtils.isEmpty(cache)){
return point.proceed();
}
String requestUri = request.getRequestURI();
for(AspectCacheDto item : cache){
if(UrlUtil.urlMatcher(item.getUrl(),requestUri)){
String cacheKey = createCacheKey(point, requestUri);
Object result = redisUtil.get(cacheKey);
if(null == result){
result = point.proceed();
redisUtil.set(cacheKey,result,item.getTime());
}else {
log.info("接口从缓存中获取的结果,缓存的key为:{}",cacheKey);
}
return result;
}
}
return point.proceed();
}
private String createCacheKey(ProceedingJoinPoint point,String requestUri){
Map map = getParameterStr(point);
StringJoiner sb = new StringJoiner("&","?","");
if(null != map && map.size() > 0){
map.forEach((key,value)->{
if(value.startsWith("\"")){
value = value.replaceAll("\"","");
}
sb.add(key+"="+value);
});
}
return CACHE_PREFIX+requestUri+"_"+sb.toString();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy