簡體   English   中英

Spring-boot micrometer timer() 它是如何工作的?

[英]Spring-boot micrometer timer() how does it work?

我是使用 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

還有千分尺依賴項: '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);

這有效:

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

 didSomeLogic;
 long t = timeOccurred - timeScheduled;
 LOG.info("recorded timer = {}", t);
});

請參閱文檔的這一部分 我對其進行了調整,使其與您想要的更相似。 您只需使用AutoConfigured MetricRegistry注冊您的Timer

@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);
    }

}

這可能是。 如果您使用的是 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());
}

使用 Spring Boot Micrometer 輸出計時器信息的另一種方法是將注釋io.micrometer.core.annotation.Timed添加到要跟蹤其執行的方法中,並添加到 ApplicationContext 類中,或添加到任何具有@Configuration類中注解,方法如下:

@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}

之后,一個工作示例將是:

@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);
}

另請參閱此答案: https : //stackoverflow.com/a/49193908/5538923

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM