springboot 自定义注解记录控制器执行时间(aop实现)

2022-08-02,,,,


springboot 自定义注解记录控制器执行时间(aop实现)

 

 

**********************

示例

 

******************

myannotation 层

 

@LogRecord:自定义注解记录控制器执行时间

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogRecord {

    String methodDesc() default "";
}

 

******************

aspect 层

 

CustomAspect

@Aspect
@Component
public class CustomAspect {

    private final Logger logger= LoggerFactory.getLogger(CustomAspect.class.getName());

    private final ThreadLocal<Long> threadLocal=new ThreadLocal<>();

    @Pointcut("@annotation(com.example.demo.myannotation.LogRecord)")
    public void fun(){

    }

    @Before("fun()")
    public void before(JoinPoint joinPoint){
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        Method method=methodSignature.getMethod();

        LogRecord logRecord=method.getAnnotation(LogRecord.class);
        if (logRecord!=null){
            threadLocal.set(System.currentTimeMillis());
        }
    }

    @After(("fun()"))
    public void after(JoinPoint joinPoint){
        Method method=((MethodSignature)joinPoint.getSignature()).getMethod();

        LogRecord logRecord=method.getAnnotation(LogRecord.class);
        if (logRecord!=null){
            Long startTime=threadLocal.get();
            Long endTime=System.currentTimeMillis();
            Long costTime=endTime-startTime;

            String requestUri=method.getAnnotation(RequestMapping.class).value()[0];
            String methodName=method.getDeclaringClass().getName()+"."+method.getName();
            String methodDesc=logRecord.methodDesc();

            logger.info("requestUri({}) methodName({}) methodDesc({}) ==> 花费时间 {}ms",requestUri,methodName,methodDesc,costTime);
        }
    }
}

 

******************

controller 层

 

HelloController

@RestController
public class HelloController {

    @LogRecord(methodDesc = "hello")
    @RequestMapping("/hello")
    public String hello() throws Exception{
        System.out.println("hello");
        TimeUnit.SECONDS.sleep(4);

        return "hello";
    }
}

 

 

**********************

使用测试

 

localost:8080/hello

2020-07-16 15:35:40.790  INFO 13748 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 7 ms
hello
2020-07-16 15:35:44.846  INFO 13748 --- [nio-8080-exec-1] com.example.demo.aop.CustomAspect        : requestUri(/hello) methodName(com.example.demo.controller.HelloController.hello) methodDesc(hello) ==> 花费时间 4020ms

/hello 执行花费时间 4020ms

 

 

本文地址:https://blog.csdn.net/weixin_43931625/article/details/107378090

《springboot 自定义注解记录控制器执行时间(aop实现).doc》

下载本文的Word格式文档,以方便收藏与打印。