使用註解的方式實現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

相關文章
相關標籤/搜索