起因
在一次排查接口请求较慢的问题时,发现没有打印请求耗时,而涉及的接口又比较多,无法所有接口都进行更改排查,所以用AOP技术在这个场景进行简单计算就非常的方便,无需改动原有接口
示例
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* 对所有接口的请求响应做切面处理
*/
@Aspect
@Configuration
public class RequestAopConfig {
protected Logger log = LoggerFactory.getLogger(this.getClass());
@Resource
private HttpServletRequest request;
private static final ThreadLocal<Long> START_TIME_MILLIS = new ThreadLocal<>();
@Pointcut("execution(* com.springmvc.controller..*.*(..))")
public void controllerMethodPointcut() {
}
/**
* 前置通知
*/
@Before("controllerMethodPointcut()")
public void before(JoinPoint joinPoint) {
START_TIME_MILLIS.set(System.currentTimeMillis());
}
/**
* 后置通知
*/
@AfterReturning(value = "controllerMethodPointcut()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
String logTemplate = "\n请求开始---URL: {}, Method: {}, Params: {} \n请求方法---ClassName: {}, [Method]: {}, execution time: {}ms \n请求结束---Result: {}";
log.info(logTemplate, request.getRequestURL(), request.getMethod(), joinPoint.getArgs(), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), (System.currentTimeMillis() - START_TIME_MILLIS.get()), JSON.toJSONString(result));
START_TIME_MILLIS.remove();
}
/**
* 异常通知
*/
@AfterThrowing(value = "controllerMethodPointcut()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
String logTemplate = "--------------- 执行失败 ---------------\n异常请求开始---Send Request URL: {}, Method: {}, Params: {} \n异常请求方法---ClassName: {}, [Method]: {}, execution time: {}ms \n异常请求结束---Exception Message: {}";
log.error(logTemplate, request.getRequestURL(), request.getMethod(), joinPoint.getArgs(), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), (System.currentTimeMillis() - START_TIME_MILLIS.get()), ex.getMessage());
START_TIME_MILLIS.remove();
}
/**
* 最终通知
*/
@After("controllerMethodPointcut()")
public void after(JoinPoint joinPoint) {
}
}