java 时间周期控制器_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 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

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值