利用切面计算方法耗时
- 一、引入依赖
- 二、创建注解
- 三、创建切面
- 四、controller测试
- 五、结果输出
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、创建注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeConsume {
}
三、创建切面
@Slf4j
@Aspect
@Component
public class TimeConsumeAspect {
@Around("@annotation(org.example.annotation.TimeConsume)")
public Object executionTimeLogger(ProceedingJoinPoint joinPoint) {
try {
long startTime = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = (System.currentTimeMillis() - startTime);
log.info("{}方法在{}毫秒内执行完毕", joinPoint.getSignature(), executionTime);
return proceed;
} catch (Throwable e) {
log.error("在计算{}方法执行时间时出错", joinPoint.getSignature(), e);
return null;
}
}
}
四、controller测试
@RestController
public class TestSpiController {
@TimeConsume
@GetMapping("/test")
public void myMethod() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
五、结果输出