diff --git a/src/main/java/com/sample/controller/SampleController.java b/src/main/java/com/sample/controller/SampleController.java index b92ff3a..768fd1c 100644 --- a/src/main/java/com/sample/controller/SampleController.java +++ b/src/main/java/com/sample/controller/SampleController.java @@ -1,9 +1,12 @@ package com.sample.controller; import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Timer; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.prometheus.client.exporter.common.TextFormat; +import java.util.Random; +import java.util.concurrent.TimeUnit; import lombok.Data; import lombok.Builder; import org.springframework.http.HttpHeaders; @@ -17,30 +20,44 @@ @RequestMapping("/sample") public class SampleController { - private final PrometheusMeterRegistry prometheusMeterRegistry; - private final Counter helloCounter; + private final PrometheusMeterRegistry prometheusMeterRegistry; + private final Counter helloCounter; - public SampleController() { - prometheusMeterRegistry= new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); - helloCounter = prometheusMeterRegistry.counter("hoge.counter", "group", "A", "sub-group", "B"); - } + public SampleController() { + prometheusMeterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); + helloCounter = prometheusMeterRegistry.counter("hoge.counter", "group", "A", "sub-group", "B"); + } - @GetMapping("/prometheus") - public ResponseEntity prometheus() { - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004) - .body(prometheusMeterRegistry.scrape()); - } + @GetMapping("/prometheus") + public ResponseEntity prometheus() { + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004) + .body(prometheusMeterRegistry.scrape()); + } - @GetMapping("/hello") - public SampleDto hello() { - helloCounter.increment(); - return SampleDto.builder().msg("hello").build(); - } + @GetMapping("/hello") + public SampleDto hello() { + helloCounter.increment(); + Timer.builder("hoge.timer") + .tag("group", "A") + .publishPercentiles(0.5, 0.95, 0.99) + .register(prometheusMeterRegistry) + .record(() -> { + try { + Random rand = new Random(); + int num = rand.nextInt(3); + TimeUnit.SECONDS.sleep(num + 1); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + return SampleDto.builder().msg("hello").build(); + } - @Builder - @Data - private static class SampleDto { - private String msg; - } + @Builder + @Data + private static class SampleDto { + + private String msg; + } }