springboot 自定义注解记录控制器执行时间(aop实现)
程序员文章站
2022-04-09 23:38:56
springboot自定义注解记录控制器执行时间(aop实现)...
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