Newer
Older
sample-prometheus2 / src / main / java / com / sample / controller / SampleController.java
yhornisse on 29 Apr 2021 1 KB add files
package com.sample.controller;

import io.micrometer.core.instrument.Counter;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import lombok.Builder;
import lombok.Data;
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 prometheusMeterRegistry) {
        this.prometheusMeterRegistry = prometheusMeterRegistry;
        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();
        return SampleDto.builder().msg("hello").build();
    }

    @Builder
    @Data
    private static class SampleDto {
        private String msg;
    }
}