如何在 Java 应用程序中在 Spring 之外使用 Micrometer @Timed 注释 [英] How to use Micrometer @Timed annotation outside of Spring, in a Java Application
问题描述
我正在尝试使用 Micrometer 在我的 Java 应用程序中记录信息.
I am trying to use Micrometer to record info in my Java application.
我的应用程序主目录中有 Micrometer 注册表初始化如下:
I have Micrometer registry in my application main initialized as follows:
MeterRegistry registry = new SimpleMeterRegistry();
我有一个 CountedObject 类,它有一个 int id 和一个对 注册表 的引用.
I have a class CountedObject which has an int id and a reference to the registry.
在我的班级 CountedObject 中,我有一个名为 timedFunction() 的方法,如下所示:
In my class CountedObject I have a method called timedFunction() as follows:
@Timed(value = "myTimer")
public void timedFunction() {
try {
int sleepTime = new Random().nextInt(5) + 1;
Thread.sleep(sleepTime * 1000L);
} catch (InterruptedException e) {}
System.out.println("timedFunction");
}
还有一个名为timedFunction()的方法如下:
And a method called timedFunction() as follows:
public void timeConsumingFunction() {
LongTaskTimer longTaskTimer = AppMetrics.getInstance().getLongTaskTimer("longTaskTimer1");
Sample task = longTaskTimer.start();
try {
int sleepTime = new Random().nextInt(5) + 1;
Thread.sleep(sleepTime * 1000L);
} catch (InterruptedException e) {}
System.out.println("timeConsumingFunction() for object-" + id + " took: " + task.duration(TimeUnit.SECONDS));
task.stop();
}
在我的应用程序中,我创建了一个对象 CountedObject 并运行这两种方法.
In my application I create an object CountedObject and run both methods.
然后我运行以下命令来打印所有指标信息:
Then I run the following to print all metrics info:
List<Meter> meters = registry.getMeters();
for (Meter meter : meters) {
System.out.println(meter.getId());
for (Measurement measurement : meter.measure()) {
System.out.println(measurement.getStatistic() + " : " + measurement.getValue());
}
System.out.println("\n");
}
我只在指标中找到了 "longTaskTimer1" 而在注释方法中使用的 myTimer 不存在.如何使用此 @Timed 注释以及如何将其链接到我的应用程序的寄存器
I only find "longTaskTimer1" in the metrics and myTimer used in the annotated method is not there. How can this @Timed annotation be used and how to link it to my app's register
推荐答案
您需要设置 TimedAspect
来处理 @Timed
注释.如果您使用的是 Spring,只需创建一个 TimedAspect
@Bean
就可以了.如果不这样做,则需要自己设置 AspectJ.
You need to set-up TimedAspect
to process @Timed
annotations.
If you are using Spring, just create a TimedAspect
@Bean
and it should work. If you don't, you need to set-up AspectJ yourself.
这篇关于如何在 Java 应用程序中在 Spring 之外使用 Micrometer @Timed 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!