【发布时间】:2021-06-02 10:51:38
【问题描述】:
我正在尝试使用Micrometer 在我的 Java 应用程序中记录执行时间。这与我的其他question 关于使用的@Timed 注释有关。
我有一个类CountedObject,它有以下两种方法:
@Measured
@Timed(value = "timer1")
public void measuredFunction() {
try {
int sleepTime = new Random().nextInt(3) + 1;
Thread.sleep(sleepTime * 1000L);
} catch (InterruptedException e) {}
}
@Timed(value = "timer2")
public void timedFunction() {
try {
int sleepTime = new Random().nextInt(3) + 1;
Thread.sleep(sleepTime * 1000L);
} catch (InterruptedException e) {}
}
我已经定义了一个自定义注解@Measured
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Measured {
}
还有一个MeasuredAspect 来拦截对使用我的@Measured 注释进行注释的方法的调用:
@Aspect
public class MeasuredAspect {
@Around("execution(* *(..)) && @annotation(Measured)")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
return AppMetrics.getInstance().handle(pjp);
}
}
在我的AppMetrics 类中,我初始化了千分尺的TimedAspect 实例,并在handle(ProceedingJoinPoint pjp) 方法中将ProceedingJoinPoint pjp 传递给TimedAspect 实例。
public class AppMetrics {
private static final AppMetrics instance = new AppMetrics();
private MeterRegistry registry;
private TimedAspect timedAspect;
public static AppMetrics getInstance() {
return instance;
}
private AppMetrics() {
this.registry = new SimpleMeterRegistry();
this.timedAspect = new TimedAspect(registry);
}
public Object handle(ProceedingJoinPoint pjp) throws Throwable {
return timedAspect.timedMethod(pjp);
}
}
在我的应用程序主程序中,我创建了一个 CountedObject 对象并调用 measuredFunction() 和 timedFunction() 然后我检查了我的 registry.getMeters(); 仅 timer1 使用 measuredFunction() [这是找到了@Measured 和@Timed 都注释的],而timedFunction() [仅由@Timed 注释] 应该使用的timer2 不存在。
我正在使用带有AspectJ Development Tools Plugin 的eclipse,我的项目是一个具有AspectJ 功能的Gradle 项目。我在我的 Gradle 插件中使用 id "io.freefair.aspectj" version "5.1.1" 插件。这是一个基本的 Java 应用程序,而不是 Spring 应用程序。
需要进行哪些配置或需要更改哪些代码,以便千分尺TimedAspect 可以直接拦截我的方法调用[即timedFunction() 应该定时并且应该在注册表中找到timer2 ] 不需要我的自定义注释?
【问题讨论】:
标签: java aop aspectj micrometer