我计划记录 REST API 的所有方法的执行时间。为了实现这一点,我使用 AOP,如下所示:
@Aspect
@Component
@Slf4j
@ConditionalOnExpression("${aspect.enabled:true}")
public class ExecutionTimeAdvice {
@Around("@annotation(TrackExecutionTime)")
public Object executionTime(ProceedingJoinPoint point) throws Throwable {
long startTime = System.currentTimeMillis();
Object object = point.proceed();
long endtime = System.currentTimeMillis();
log.info("Class Name: " + point.getSignature().getDeclaringTypeName() + ". Method Name: " + point.getSignature().getName() + ". Time taken for Execution is : " + (endtime - startTime) + "ms");
return object;
}
}
@Service
public class MessageService {
@TrackExecutionTime
@Override
public List<AlbumEntity> getMessage() {
return "Hello message";
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
但是使用 AOP 会带来性能开销。服务响应时间存在200ms以上的滞后,即性能开销。
有人可以向我建议一种实现执行时间日志记录的有效方法吗?我可以使用 AspectJ 来提高效率吗?或者有什么AOP的替代方案吗?我们能否以更高效的方式使用AOP?
如果您包含 Micrometer、Prometheus 和 Spring Boot Actuator,您可能会减少 200+ms 的开销。我的猜测是 200+ms 的开销是由于日志记录造成的。 这篇文章很好地描述了如何使用
@Timed
注释来测量公共方法的执行时间。当您点击执行器/promethius 端点时,会显示计时器信息,例如最大和总执行时间以及事件数量。您可以根据事件总数和数量得出平均值。