上篇文章說到使用原生的StopWatch查看程序執行時間,本文將介紹使用註解+AOP(面向切面編程)的方式實現其功能,一來能夠快速使用StopWatch功能,二來讓你們熟悉一下如何使用註解進行切面編程spring
@Retention(RetentionPolicy.RUNTIME) @Target({METHOD}) public @interface StopWatchTime { String value() default ""; }
本註解主要用在方法上,故target爲METHOD,並設定一個value,可用於定義這次觀察的名稱。編程
<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
@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