最近想统计接口运行时长然后进行接口的优化,于是就写了使用springaop统计时间的功能,上代码!记得先引入springaop依赖哦!
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.qian.wxpress.util;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Aspect
@Slf4j
public class ControllerAop {
private Date beforeDate;
private Date afterDate;
@Pointcut("execution(* com.qian.wxpress.controller..*.*(..))")
public void pointcut() {
}
@Before("pointcut()")
public void beforeAdvice() {
beforeDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(beforeDate);
}
@After("pointcut()")
public void afterAdvice() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
afterDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(afterDate);
double time = (afterDate.getTime() - beforeDate.getTime()) / 1000.0;
log.info("{} => 执行时长(单位/秒):{}", request.getRequestURI(), time);
}
}
运行结果如下图,因为数据库部署在新加坡的服务器上,所以接口响应有点慢。