前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Spring Boot整合 Prometheus

Spring Boot整合 Prometheus

作者头像
BUG弄潮儿
发布于 2021-08-13 02:04:26
发布于 2021-08-13 02:04:26
1.5K00
代码可运行
举报
文章被收录于专栏:JAVA乐园JAVA乐园
运行总次数:0
代码可运行
Micrometer简介

Micrometer 为 Java 平台上的性能数据收集提供了一个通用的 API,应用程序只需要使用 Micrometer 的通用 API 来收集性能指标即可。Micrometer 会负责完成与不同监控系统的适配工作。这就使得切换监控系统变得很容易。Micrometer 还支持推送数据到多个不同的监控系统。Micrometer类似日志系统中SLF4J。

Micrometer中有两个最核心的概念,分别是是计量器(Meter)和计量器注册表(MeterRegistry),下面来分别看下这两个概念。

计量器(Meter)

Meter用来收集性能指标数据(Metris),总共有四种类型的Meter,分别是Counter,Gauge,Timer,Summary。

每个Meter都有自己的名称,同时Meter可以指定一系列的tag。tag是以key-value的形式出现,这样我们就可以根据tag对指标进行过滤。除了每个Meter独有的标签外,也可以通过MeterRegistry添加通用的tag。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
MeterRegistry.Config config = simpleMeterRegistry.config();
    config.commonTags("tag1","value1","tag2","value2");
Counter

Counter只允许增加值,Counter所表示的计数值是double类型,默认情况下增加的值是1.0

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Autowired
private SimpleMeterRegistry simpleMeterRegistry;

@Bean
public Counter counter1(){
    return Counter.builder("test.count1").register(simpleMeterRegistry);
}

@Bean
public Counter counter2(){
    return simpleMeterRegistry.counter("test.count2");
}

@Test
public void test(){
    counter1.increment();
}
Gauge

Cauge是表示单个的变化的值,例如温度,气压。与Counter的区别在于,Gauge的值不总是增加的

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void guage(){
    Gauge.builder("guaua1", this::getValue).register(simpleMeterRegistry);
}

public double getValue(){
    return ThreadLocalRandom.current().nextDouble();
}

Gauge对象一旦被创建,就不能手动对其中的值进行修改。在每次取样时,Gauge 会返回当前值

Timer

Timer通常用来记录事件的持续时间。Timer会记录两类的数据,事件的数量和总的持续时间。Timer提供了不同方式来记录持续时间。第一种方式是使用record()方法来记录Runnable和Callable对象的运行时间,第二种方式是使用Timer.Sample来保存计时状态

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void record(){
    Timer timer = simpleMeterRegistry.timer("record");
    timer.record(() -> {
        try {
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }
    });
}

public void sample(){
    Timer.Sample sample = Timer.start();
    new Thread(()->{
        try {
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }
        sample.stop(simpleMeterRegistry.timer("sample"));
    });
}
summary

summary用来记录指标的分布,summary根据每个指标的值,把值分配到对应的bucket中。Micrometer默认的bucket的值从1到Long.MAX_VALUE,可以通过minimumExpectedValue和maximumExpectedValue来控制bucket的范围,如果指标的值较小,还可以通过scale来设置一个值对数值进行放大

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void summary(){
    DistributionSummary summary = DistributionSummary.builder("summary")
            .maximumExpectedValue(10L)
            .minimumExpectedValue(1L)
            .publishPercentiles(0.5, 0.75, 0.9)
            .register(simpleMeterRegistry);

    summary.record(1.0);
    summary.record(5.0);
    summary.record(4.5);
    summary.record(3.0);

    System.out.println(summary.takeSnapshot());
}

计量器注册表(MeterRegistry)

MeterRegistry负责创建和维护Meter。每一个监控系统有自己独有的registry

其中SimpleMeterRegistry是一个基于内存的注册表,它不支持导出数据到监控系统,主要用来进行本地开发和测试。

Micrometer支持多个不同的监控系统,通过CompositeMeterRegistry可以把多个计量器注册表组合起来,从而允许同时发布数据到多个监控系统中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void compositeRegistry(){
        CompositeMeterRegistry compositeMeterRegistry = new CompositeMeterRegistry();
        compositeMeterRegistry.add(new SimpleMeterRegistry());
        compositeMeterRegistry.add(new SimpleMeterRegistry(new SimpleConfig() {
            @Override
            public String get(String s) {
                return null;
            }

            //增加前缀
            @Override
            public String prefix() {
                return "simple";
            }
        },Clock.SYSTEM));

        Counter counter = compositeMeterRegistry.counter("test");
        counter.increment();
    }

Micrometer本身提供了一个静态的全局注册表Metrics.golbalRegistry。这个注册表一个组合注册表,使用Metrics类中的静态方法创建的计量器,都会被添加到这个全局注册表中

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public void globalRegistry(){
    Metrics.addRegistry(simpleMeterRegistry);
    Counter global = Metrics.counter("global");
    global.increment();
}

SpringBoot Actuator

上述介绍了Micrometer的一些简单使用,从Spring Boot2.0开始,Micrometer就是Spring Boot默认提供的性能指标收集库。SpringBoot Actuator提供了对Micrometer的自动配置。在项目中引入SpringBoot Actuator,

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

并在配置文件中,增加如下配置

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Actuator可对外默认的服务,*表示显示所有
management.endpoints.web.exposure.include=*

启动项目,访问http://8080/actuator,就可以看到Actuator提供的所有监控

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "auditevents": {
      "href": "http://localhost:8080/actuator/auditevents",
      "templated": false
    },
    "beans": {
      "href": "http://localhost:8080/actuator/beans",
      "templated": false
    },
    "caches-cache": {
      "href": "http://localhost:8080/actuator/caches/{cache}",
      "templated": true
    },
    "caches": {
      "href": "http://localhost:8080/actuator/caches",
      "templated": false
    },
    "health": {
      "href": "http://localhost:8080/actuator/health",
      "templated": false
    },
    "health-component": {
      "href": "http://localhost:8080/actuator/health/{component}",
      "templated": true
    },
    "health-component-instance": {
      "href": "http://localhost:8080/actuator/health/{component}/{instance}",
      "templated": true
    },
    "conditions": {
      "href": "http://localhost:8080/actuator/conditions",
      "templated": false
    },
    "configprops": {
      "href": "http://localhost:8080/actuator/configprops",
      "templated": false
    },
    "env": {
      "href": "http://localhost:8080/actuator/env",
      "templated": false
    },
    "env-toMatch": {
      "href": "http://localhost:8080/actuator/env/{toMatch}",
      "templated": true
    },
    "info": {
      "href": "http://localhost:8080/actuator/info",
      "templated": false
    },
    "loggers": {
      "href": "http://localhost:8080/actuator/loggers",
      "templated": false
    },
    "loggers-name": {
      "href": "http://localhost:8080/actuator/loggers/{name}",
      "templated": true
    },
    "heapdump": {
      "href": "http://localhost:8080/actuator/heapdump",
      "templated": false
    },
    "threaddump": {
      "href": "http://localhost:8080/actuator/threaddump",
      "templated": false
    },
    "prometheus": {
      "href": "http://localhost:8080/actuator/prometheus",
      "templated": false
    },
    "metrics": {
      "href": "http://localhost:8080/actuator/metrics",
      "templated": false
    },
    "metrics-requiredMetricName": {
      "href": "http://localhost:8080/actuator/metrics/{requiredMetricName}",
      "templated": true
    },
    "scheduledtasks": {
      "href": "http://localhost:8080/actuator/scheduledtasks",
      "templated": false
    },
    "httptrace": {
      "href": "http://localhost:8080/actuator/httptrace",
      "templated": false
    },
    "mappings": {
      "href": "http://localhost:8080/actuator/mappings",
      "templated": false
    }
  }
}

访问http://localhost:8080/actuator/metrics,可以看到Actuator默认收集的监控指标,包括JVM相关指标(内存使用,垃圾收集),tomcat相关指标,数据库连接池还是系统相关指标

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
  "names": [
    "jvm.memory.max",
    "jvm.threads.states",
    "process.files.max",
    "jvm.gc.memory.promoted",
    "system.load.average.1m",
    "jvm.memory.used",
    "jvm.gc.max.data.size",
    "jvm.gc.pause",
    "jvm.memory.committed",
    "system.cpu.count",
    "logback.events",
    "tomcat.global.sent",
    "jvm.buffer.memory.used",
    "tomcat.sessions.created",
    "jvm.threads.daemon",
    "system.cpu.usage",
    "jvm.gc.memory.allocated",
    "tomcat.global.request.max",
    "tomcat.global.request",
    "tomcat.sessions.expired",
    "jvm.threads.live",
    "jvm.threads.peak",
    "tomcat.global.received",
    "process.uptime",
    "tomcat.sessions.rejected",
    "process.cpu.usage",
    "http.server.requests",
    "tomcat.threads.config.max",
    "jvm.classes.loaded",
    "jvm.classes.unloaded",
    "tomcat.global.error",
    "tomcat.sessions.active.current",
    "tomcat.sessions.alive.max",
    "jvm.gc.live.data.size",
    "tomcat.threads.current",
    "process.files.open",
    "jvm.buffer.count",
    "jvm.buffer.total.capacity",
    "tomcat.sessions.active.max",
    "tomcat.threads.busy",
    "process.start.time"
  ]
}

我们可以通过以下链接来查看具体某个指标

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
http://localhost:8080/actuator/metrics/metricName

其中metricName为需要查看指标的名称,例如查看jvm内存

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 http://localhost:8080/actuator/metrics/jvm.memory.used

从上图中我们可以看到jvm.memory.used有两个tag,area和id,area指定内存位置(堆内存和非堆内存),id指定内存分类,我们可以指定tag来查看更细致的指标

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
http://localhost:8080/actuator/metrics/jvm.memory.used?tag=area:heap
http://localhost:8080/actuator/metrics/jvm.memory.used?tag=area:heap&tag=id:PS%20Eden%20Space

Prometheus

Micrometer支持Prometheus,Micrometer提供PrometheusMeterRegistry注册表,用于将指标转为Prometheus格式的指标。首先需要在pom文件引入依赖

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

其次在配置文件中,配置暴露Prometheus,并允许将指标导入到Prometheus中

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true

项目启动后,我们访问http://localhost:8080/actuator/prometheus,可以看到指标以变成Prometheus格式的指标

可以安装Prometheus来采集这些指标

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
docker run -d -p 9090:9090 -v ~/Documents/config/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

其中prometheus.yml配置了采集地址及路径

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
scrape_configs:
 - job_name: prometheus-test
   metrics_path: /actuator/prometheus
   static_configs:
   - targets: ['172.16.22.50:8080']

172.16.22.50是我本机的地址,你们可以修改为自己的ip地址即可,访问http://localhost:9090/targets可以看到Prometheus采集配置

自定义Metric

我们可以利用Prometheus client自定义metric

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.wbl.spingbootdemo.prometheus;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author wbl
 * @date 2019-09-29
 */
@Service
public class PrometheusMeter {

    @Autowired
    private CollectorRegistry collectorRegistry;

    // 定义name为prometheus_counter的counter
    public Counter prometheusCounter(){
        return Counter.build().name("prometheus_counter").help("prometheus counter test")
                .register(collectorRegistry);
    }

    @PostConstruct
    public void init(){
        Counter counter = prometheusCounter();
        new Thread(()-> {
            while (true){
                counter.inc();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

启动项目之后,可以在Prometheus查询页面看到刚刚定义的指标prometheus_counter

总结

  1. Micrometer整合了多个监控系统,包括Prometheus。Micrometer利用Meter收集数据,利用不同的MeterRegistry与不同的监控系统整合
  2. SpringBoot Actuator集成了Micrometer,定义了许多默认的metric,可以在http://localhost:8080/actuator/metrics查看
  3. SpringBoot Actuator可以通过Micrometer将采集的指标导入到Prometheus中

参考文献

  • Micrometer
  • Quick Guide to Micrometer
  • Instrumenting And Monitoring Spring Boot 2 Applications
  • 自定义Metrics:让Prometheus监控你的应用程序
  • 使用 Micrometer 记录 Java 应用性能指标
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 BUG弄潮儿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
编辑精选文章
换一批
SpringBoot - 构建监控体系02_定义度量指标和 Actuator 端点
SpringBoot - 构建监控体系01_使用 Actuator 组件实现及扩展系统监控 我们引入了 Spring Boot Actuator 组件来满足 Spring Boot 应用程序的系统监控功能,并重点介绍了如何扩展常见的 Info 和 Health 监控端点的实现方法。
小小工匠
2021/08/17
9830
SpringBoot - 构建监控体系02_定义度量指标和 Actuator 端点
Spring Boot 使用 Micrometer 集成 Prometheus 监控 Java 应用性能
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
哎_小羊
2019/09/18
10.5K0
Spring Boot 使用 Micrometer 集成 Prometheus 监控 Java 应用性能
给你的SpringBoot做埋点监控--JVM应用度量框架Micrometer
spring-actuator做度量统计收集,使用Prometheus(普罗米修斯)进行数据收集,Grafana(增强ui)进行数据展示,用于监控生成环境机器的性能指标和业务数据指标。一般,我们叫这样的操作为”埋点”。SpringBoot中的依赖spring-actuator中集成的度量统计API使用的框架是Micrometer,官网是Micrometer.io。在实践中发现了业务开发者滥用了Micrometer的度量类型Counter,导致无论什么情况下都只使用计数统计的功能。这篇文章就是基于Micrometer分析其他的度量类型API的作用和适用场景。
云扬四海
2019/08/14
5.3K0
SpringBoot Actuator — 埋点和监控
监控机器环境的性能和业务流程或逻辑等各项数据,并根据这些数据生成对应的指标,那么我们就称为数据埋点。比如我们想知道某个接口调用的 TPS、机器 CPU 的使用率,这些都可以用到数据埋点
晚上没宵夜
2021/11/16
1.4K0
Spring Boot Actuators
Spring Boot 提供了开箱即用的应用监控功能,对于大厂来说可能比较鸡肋,但是对于一些没有基础建设团队的中小公司是非常好用的。
李鸿坤
2020/09/24
3830
Spring学习笔记(二十九)——SpringBoot Actuator指标监控
在项目上线后,或者未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
不愿意做鱼的小鲸鱼
2022/09/26
1.2K0
Spring学习笔记(二十九)——SpringBoot Actuator指标监控
基于Prometheus搭建SpringCloud全方位立体监控体系
最近公司在联合运维做一套全方位监控的系统,应用集群的技术栈是SpringCloud体系。虽然本人没有参与具体基础架构的研发,但是从应用引入的包和一些资料的查阅大致推算出具体的实现方案,这里做一次推演,详细记录一下整个搭建过程。
Throwable
2020/06/23
2.7K0
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!
  通过前面的介绍我们明白了SpringBoot为什么能够很方便快捷的构建Web应用,那么应用部署上线后的健康问题怎么发现呢?在SpringBoot中给我们提供了Actuator来解决这个问题。
用户4919348
2021/09/08
1.6K0
SpringBoot掌握的差不多了,就剩下一个Actuator没搞定了,本文详细来介绍!!!
可观测性神器之 Micrometer
对于大部分开发人员来说可能用过普罗米修斯Grafana这样的监控系统,从未听说过Micrometer工具,这里就详细的来介绍下可观测性神器Micrometer,让你在开发时使用它就和使用SLFJ 日志系统一样简单易用,有效的提升系统的健壮性和可靠性。
宋小生
2022/12/05
1.8K0
可观测性神器之 Micrometer
Spring Boot Actuator
Spring Boot Actuator 在Spring Boot第一个版本发布的时候就有了,它为Spring Boot提供了一系列产品级的特性:监控应用程序,收集元数据,运行情况或者数据库状态等。
程序那些事
2020/07/07
6550
Prometheus + Grafana 监控 SpringBoot
Prometheus 是监控系统,可以从 Springboot 获取监控数据,以时序数据的形式存储,并提供了监控数据的查询服务。
dys
2020/02/19
2K0
彻底搞懂监控系统,使用Prometheus监控Spring Boot应用,自定义应用监控指标!
前面我们介绍了使用Prometheus + Grafana 构建了监控系统,那么我们的应用平台怎么监控呢?应用平台中的核心业务的执行情况能否监控呢?那么接下来我们使用Actuator,Micrometer,Prometheus和Grafana监控Spring Boot应用程序,自定义应用监控指标。
架构师精进
2023/03/23
15K2
彻底搞懂监控系统,使用Prometheus监控Spring Boot应用,自定义应用监控指标!
重学SpringBoot3-集成Spring Boot Actuator
Spring Boot Actuator 是 Spring Boot 提供的一组内置功能,用于监控和管理应用程序。通过 Actuator,开发者可以轻松获取应用的运行时状态,执行健康检查,监控性能指标,甚至自定义端点来满足特定需求。本文将详细介绍如何在 Spring Boot 3 中整合 Spring Boot Actuator,并展示如何配置和使用 Actuator 提供的核心功能。
CoderJia
2024/10/18
3960
重学SpringBoot3-集成Spring Boot Actuator
Spring Boot Actuator解析
Actuator 是 SpringBoot 项目中一个非常强大一个功能,有助于对应用程序进行监视和管理,通过 Restful Api 请求来监管、审计、收集应用的运行情况。
Luga Lee
2021/12/09
9820
Spring Boot Actuator解析
优秀,一招搞定 Spring Boot 可视化监控!
当某个应用程序在生产环境中运行时,监控其运行状况是必要的。通过实时了解应用程序的运行状况,你能在问题出现之前得到警告,也可以在客户注意到问题之前解决问题。
终码一生
2022/04/15
2.2K0
优秀,一招搞定 Spring Boot 可视化监控!
Spring Boot Actuator 介绍-Spring Boot教程深入浅出系列
在本文中,我们介绍了 Spring Boot Actuator。我们将首先介绍基础知识,然后详细讨论 Spring Boot 2.x 与 1.x 中可用的内容。
jack.yang
2025/04/05
1510
SpringBoot+Prometheus:微服务开发中自定义业务监控指标的几点经验
从马楠的上一篇文章中,我们已经了解到Prometheus的一大优势,是可以在应用内定义自己的指标做监控。我们在 SpringBoot 做微服务的生产环境中,使用自定义指标监控诸多物联网传感器,时序数据结构简单清晰,监控与统计反应迅捷,效果良好。
王录华
2019/07/31
16.2K0
SpringBoot+Prometheus:微服务开发中自定义业务监控指标的几点经验
聊聊springboot2的micrometer
springboot2在spring-boot-actuator中引入了micrometer,对1.x的metrics进行了重构,另外支持对接的监控系统也更加丰富(Atlas、Datadog、Ganglia、Graphite、Influx、JMX、NewRelic、Prometheus、SignalFx、StatsD、Wavefront)。1.x的metrics都有点对齐dropwizard-metrics的味道,而micrometer除了一些基本metrics与dropwizard-metrics相类似外,重点支持了tag。这是一个很重要的信号,标志着老一代的statsd、graphite逐步让步于支持tag的influx以及prometheus。
code4it
2018/09/17
2.2K0
Spring Boot Actuator监控使用详解
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
程序新视界
2019/11/20
1.9K0
springboot2上报metrics到statsd
micrometer-registry-statsd-1.0.1-sources.jar!/io/micrometer/statsd/StatsdFlavor.java
code4it
2018/09/17
1.3K0
推荐阅读
相关推荐
SpringBoot - 构建监控体系02_定义度量指标和 Actuator 端点
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验