@Aspect
@Component
@Lazy(false)
public class ApiCallAdvice {
private static final String FORMAT_PATTERN_DAY = "yyyy-MM-dd";
private static final String FORMAT_PATTERN_HOUR = "yyyy-MM-dd HH";
private static final String FORMAT_PATTERN_MILLS = "yyyy-MM-dd HH:mm:ss:SSS";
private static final Logger logger = Logger.getLogger(ApiCallAdvice.class);
@AfterReturning("execution(* com.demo.controller.*.*(..))")
protected void afterReturning() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI();
String date_day = dateFormat(FORMAT_PATTERN_DAY);
String date_hour = dateFormat(FORMAT_PATTERN_HOUR);
Redis.getInstance().hIncrement(uri, date_day);
Redis.getInstance().hIncrement(uri, date_hour);
}
@AfterThrowing(value = "execution(* com.demo.controller.*.*(..))", throwing = "ex")
protected void afterThrowing(Exception ex) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI() + "_exception";
String time = dateFormat(FORMAT_PATTERN_MILLS);
String exception = ex.getMessage();
Redis.getInstance().hset(uri, time, exception);
}
@Around("execution(* com.demo.controller.*.*(..))")
protected Object around(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String requestURI = request.getRequestURI();
Signature signature = joinPoint.getSignature();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try {
Object result = joinPoint.proceed();
stopWatch.stop();
logger.info("接口:" +requestURI + "; 方法名:"+signature.getName()+ "; cost: " + stopWatch.getTotalTimeSeconds() + "秒");
return result;
} catch (Exception e) {
logger.error(e);
throw e;
}
}
private String dateFormat(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
}
以上代码是为了测试使用,如果实际生产环境,有其他方法监控调用等信息。感兴趣了解全链路监控
本文大部分内容来自
|