弹簧引导千分尺timer()如何工作?

ano*_*rer 2 spring-boot spring-boot-actuator micrometer

我是使用Spring Boot指标的新手,从千分尺开始。我找不到在我的spring-boot应用程序中执行计时器指标的好例子(事实是它的新特性)。我正在使用spring-boot-starter-web:2.0.2.RELEASE依赖项。但是运行spring-boot服务器并启动jconsole时,我没有看到它显示Metrics(MBeans),因此我还明确地将以下依赖项包括在内:

spring-boot-starter-actuator:2.0.2.RELEASE
Run Code Online (Sandbox Code Playgroud)

还有千分尺的依赖性:'io.micrometer:micrometer-registry-jmx:latest' 添加执行器后,它确实显示Metrics文件夹,但列表中没有看到我的timer(app.timer)属性。难道我做错了什么?任何建议表示赞赏!

下面的代码段:

MeterRegistry registry = new CompositeMeterRegistry();
long start = System.currentTimeMillis();
Timer timer = registry.timer("app.timer", "type", "ping");
timer.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)

这有效:

Metrics.timer("app.timer").record(()-> {

 didSomeLogic;
 long t = timeOccurred - timeScheduled;
 LOG.info("recorded timer = {}", t);
});
Run Code Online (Sandbox Code Playgroud)

Ali*_*nka 10

这可能是。如果您使用 Spring Boot 2,只需在任意位置调用 Timer 即可,无需使用构造函数。

public void methodName(){
    //start
    Stopwatch stopwatch = Stopwatch.createStarted();// Google Guava
    
    // your job here
         
    // check time
    Metrics.timer("metric-name",
            "tag1", this.getClass().getSimpleName(), //class
            "tag2", new Exception().getStackTrace()[0].getMethodName()) // method 
            .record(stopwatch.stop().elapsed());
}
Run Code Online (Sandbox Code Playgroud)


Dov*_*vmo 5

请参阅文档的这一部分。我将其调整为与您想要的内容更加相似。您只需要在上注册您TimerAutoConfigured MetricRegistry

@Component
public class SampleBean {

    private final Timer timer;

    public SampleBean(MeterRegistry registry) {
        long start = System.currentTimeMillis();
        this.timer = registry.timer("app.timer", "type", "ping");
    }

    public void handleMessage(String message) {
        timer.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 Spring Boot Micrometer 输出计时器信息的另一种方法是将注释添加io.micrometer.core.annotation.Timed到要跟踪执行情况的方法中,并在 ApplicationContext 类或任何具有注释的类中添加@Configuration以下方法:

@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}
Run Code Online (Sandbox Code Playgroud)

之后,一个有效的例子是:

@PostMapping(value = "/save", produces = "application/json")
@Timed(description = "Time spent saving results")
public ResponseEntity<Integer> saveResults(@CookieValue(name = "JSESSIONID") String sessionId) {
    return new ResponseEntity<>(importer.saveResults(sessionId), HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此答案:https ://stackoverflow.com/a/49193908/5538923 。

  • 但这不允许在执行中添加动态标签 (2认同)