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; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/sample") public class SampleController { 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"); } @GetMapping("/prometheus") public ResponseEntity<String> prometheus() { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004) .body(prometheusMeterRegistry.scrape()); } @GetMapping("/hello") public SampleDto hello() { helloCounter.increment(); Timer.builder("hoge.timer") .tag("group", "A") .publishPercentiles(0.5, 0.75, 0.95) .register(prometheusMeterRegistry) .record(() -> { try { Random rand = new Random(); TimeUnit.MILLISECONDS.sleep(rand.nextInt(500)); } catch (Exception e) { throw new RuntimeException(e); } }); return SampleDto.builder().msg("hello").build(); } @Builder @Data private static class SampleDto { private String msg; } }