AOP拦截所有请求,获取HttpServletRequest和相应结果,并统计请求耗时,成功失败情况
@Slf4j
@Aspect
@Component
public class AccessAOP {
public AccessAOP(RedisService redisService) {
this.redisService = redisService;
}
//!是排除
@Pointcut("execution(* com.xxx.controller.web..*.*(..)) " +
"&& !execution(* com.xxx.VisitLogController.*(..))"+
"&& !execution(* com.xxx.ApiLogScheduleController.*(..))"
)
public void controllerPointCut(){
//access请求切面
}
private final RedisService redisService;
@Around("controllerPointCut()")
public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
ApiResult<String> result;
String key = null;
String uri = null;
String user = null;
String resultStatus = null;
try {
final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (Objects.isNull(attributes)) {
return failed("data 参数获取失败");
}
//获取请求的request
HttpServletRequest request = attributes.getRequest();
uri = request.getRequestURI();
user = getUserInfo(request).getUser();
//获取响应结果 我强转了下
result = (ApiResult<String>) joinPoint.proceed(joinPoint.getArgs());
if (result.code == 200) {
resultStatus = "success";
}
long endTime = System.currentTimeMillis();
String statisticType = getStatisticType(endTime - startTime);
key = uri + "_" + DateUtils.getCurrentHour() + "_" + user + "_" + resultStatus + "_" + statisticType;
//写入redis,值会累加
redisService.hIncrementBy(DateUtils.getCurrentHour(),key);
return result;
}catch (Exception e){
long exceptionTime = System.currentTimeMillis();
resultStatus = "failed";
key = uri + "_" + DateUtils.getCurrentHour() + "_" + user + "_" + resultStatus + "_" + getStatisticType(exceptionTime-startTime);
throw e;
}finally {
redisService.hIncrementBy(DateUtils.getCurrentHour(),key);
}
}
public String getStatisticType(long time){
if(time<1000){
return "statistic1";
}else if(time>1000 && time<3000){
return "statistic2";
}else if(time>3000 && time<5000){
return "statistic3";
}else {
return "statistic4";
}
}
}