使用注解的方式实现StopWatch查看程序执行时间(高级篇)

上篇文章说到使用原生的StopWatch查看程序执行时间,本文将介绍使用注解+AOP(面向切面编程)的方式实现其功能,一来能够快速使用StopWatch功能,二来让你们熟悉一下如何使用注解进行切面编程spring

1. 自定义一个注解 StopWatchTime

@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD})
public @interface StopWatchTime {
    String value() default "";
}

本注解主要用在方法上,故target为METHOD,并设定一个value,可用于定义这次观察的名称。编程

2. 建立切面类

  • 引用AOP支持包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 建立切面类
@Aspect   // 1
@Component  // 2
public class StopWatchTimeAdvice {

    @Around("@annotation(stopWatchTime)")  // 3
    public Object invoke(ProceedingJoinPoint thisJoinPoint, StopWatchTime stopWatchTime) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
        String name = StringUtils.isEmpty(stopWatchTime.value()) ? methodSignature.getName() : stopWatchTime.value();  // 4

        StopWatch stopWatch = new StopWatch(name);
        stopWatch.start("00");

        Object object = thisJoinPoint.proceed();  // 5

        stopWatch.stop();
        System.err.println(stopWatch.prettyPrint());  // 6

        return object;
    }

}

代码解释spring-boot

  1. 经过@Aspect 注解声明一个切面
  2. 经过@Component 让此切面成为Spring容器管理的Bean
  3. 经过@Around注解声明一个建言,并使用定义了自定义注解@StopWatchTime的方法做为切入点
  4. 获取注解上的属性,若是无就默认当前的方法名“ methodSignature.getName() ”
  5. 做好StopWatch的前期准备后,执行切入点的方法体
  6. 执行完成后打印执行结果

3. 注解被观察方法

@StopWatchTime
    public void run(String... strings) throws Exception {
        step1();
        step2();
        step3();
    }

    private void step1() throws InterruptedException {
        Thread.sleep(100L);
    }

    private void step2() throws InterruptedException {
        Thread.sleep(850L);
    }

    private void step3() throws InterruptedException {
        Thread.sleep(2000L);
    }

只要@StopWatchTime写在哪一个方法上就能监控得出哪一个方法的执行时间,但且限于public非静态方法this

输出结果

<pre> StopWatch 'run': running time (millis) = 2985 ----------------------------------------- ms % Task name ----------------------------------------- 02985 100% 00 </pre>.net

你们可能会看出来,此方法虽然使用起来方便,但只能显示单个方法的执行时间,下一篇将告诉你们如何使用AOP的方法扩展出可同时观察一个代码段里多个方法的执行状况,敬请期待。code

相关文章
相关标签/搜索