1. 程式人生 > >SpringBoot2.x-Actutor-micrometer-自定義Mertics

SpringBoot2.x-Actutor-micrometer-自定義Mertics

前言

示例

  • 註冊 Metrics

    實現 MeterBinder 介面的 bindTo 方法,將要採集的指標註冊到 MeterRegistry

    @Component
    public class JobMetrics implements MeterBinder {
    
    
        public Counter job1Counter;
    
        public Counter job2Counter;
    
        public Map<String, Double> map;
    
        JobMetrics() {
            map = new HashMap<>();
        }
    
        @Override
    public void bindTo(MeterRegistry meterRegistry) { this.job1Counter = Counter.builder("my_job") .tags(new String[]{"name", "job1"}) .description("Job 1 execute count").register(meterRegistry); this.job2Counter = Counter.builder("my_job") .tags(new
    String[]{"name", "job2"}) .description("Job 2 execute count").register(meterRegistry); Gauge.builder("my_job_gauge", map, x -> x.get("x")) .tags("name", "job1") .description("") .register(meterRegistry); } }
  • 更新 Metrics

    示例採集了 job 執行的一些資訊。

    @Slf4j
    @Component
    public class MyJob {
    
        private Integer count1 = 0;
    
        private Integer count2 = 0;
    
        @Autowired
        private JobMetrics jobMetrics;
    
        @Async("main")
        @Scheduled(fixedDelay = 1000)
        public void doSomething() {
            count1++;
            jobMetrics.job1Counter.increment();
            jobMetrics.map.put("x", Double.valueOf(count1));
            System.out.println("task1 count:" + count1);
        }
    
        @Async
        @Scheduled(fixedDelay = 10000)
        public void doSomethingOther() {
            count2++;
            jobMetrics.job2Counter.increment();
            System.out.println("task2 count:" + count2);
        }
    }

自定義 Metrics 指標

  • Counter: 只增不減的計數器

    計數器可以用於記錄只會增加不會減少的指標型別,比如記錄應用請求的總量(http_requests_total)。

    this.job1Counter = Counter.builder("my_job") //指定指標的名稱
                    .tags(new String[]{"name", "job1"}) // 指定相同指標的不同tag
                    .description("Job 1 execute count").register(meterRegistry);
    Counter.increment()  // 每次增加1
    Counter.increment(5D) // 每次增加指定數目

    訪問 http://localhost:8080//actuator/metrics/ 可以看到新增了我們新增的指標名稱 my_job

    進入下一級目錄:http://localhost:8080//actuator/metrics/my_job ,可以看到總的執行次數是 602 ,有兩種不同的 tag

    {"name":"my_job","measurements":[{"statistic":"COUNT","value":602.0}],"availableTags":[{"tag":"name","values":["job2","job1"]}]}

    檢視 tag:job1 的詳情:http://localhost:8080//actuator/metrics/my_job?tag=name:job1

    {"name":"my_job","measurements":[{"statistic":"COUNT","value":130.0}],"availableTags":[]}
  • Gauge: 可增可減的儀表盤

    對於這類可增可減的指標,可以用於反應應用的 當前狀態,比如主機當前空閒的記憶體大小(node_memory_MemFree)

    Gauge.builder("my_job_gauge", map, x -> x.get("x"))
                    .tags("name", "job1")
                    .description("")
                    .register(meterRegistry);
    jobMetrics.map.put("x", Double.valueOf(count1));

專案地址