大多数兄弟服务上线后都没有查看JVM运行情况的习惯,或者想要对现有服务进行JVM运行时监控但没有好的方案。那么这篇文章一定要看!
本篇文章主要记录如何通过Springboot将暴露的metrics endpiont信息推送到Pushgateway,然后通过Prometheus从Pushgateway拉取监控指标在Grafana进行展示

<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_servlet</artifactId>
<version>0.12.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_pushgateway</artifactId>
<version>0.12.0</version>
</dependency>
在yaml中添加如下配置,如果已存在到就不要重复写了
spring:
application:
name: your-project-name
management:
endpoints:
web:
exposure:
# 暴露端口:metrics,其中就包含我们需要的JVM相关指标
# 如果想暴露多个示例:[health,info,metrics]
include: metrics
metrics:
tags:
application: ${spring.application.name}
export:
prometheus:
pushgateway:
#pushgateway地址
baseUrl: 127.0.0.1:8080
#推送周期
pushRate: 15s
#job定义名
job : ${spring.application.name}
#启用推送
enabled: true
该类主要作用为:增加除了metrics默认暴露的基础信息之外添加一些额外的信息
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @Description: metrics自动配置
* @Author: Eayon Lee
* @Time: 2022-07-01 14:35
**/
public class MetricsAutoConfiguration {
private static String HOST_IP = "127.0.0.1";
private static String HOST_NAME = "hostname";
@Bean
MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${spring.application.name}") String appName) {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
HOST_IP = address.getHostAddress();
HOST_NAME = address.getHostName();
} catch (UnknownHostException e) {
}
return (registry) -> {
registry.config().commonTags("hostip", HOST_IP);
registry.config().commonTags("hostname", HOST_NAME);
registry.config().commonTags("customapp", appName);
};
}
}
因为我们的SpringBoot项目启动时会连接到Pushgateway发送数据,所以我们还需要起一个Pushgateway服务
docker run -d \
--restart always \
-p 8080:9091\
-v /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime\
-v /tmp/prometheus-data:/prometheus-data/ \
--name kw_prometheus_pushgateway\
prom/pushgateway:latest
启动就完了,没啥好说的
访问Pushgateway服务地址:127.0.0.1:8080,查看是否存在对应Job(PS:该Job名称为application.yaml中配置的Job属性值)

如存在则说明配置成功
如何部署一个Prometheus这里不做赘述,大家百度就可以了。
当部署好后需要在Prometheus的配置文件中添加上我们上一步启动的Pushgateway地址后重启,配置内容如下:
scrape_configs:
# 名字随意就好
- job_name: 'pushgateway'
scrape_interval: 15s
static_configs:
- targets: ['127.0.0.1:8080']
老规矩,怎么部署一个Grafana大家百度,不做赘述,部署好后继续往下
进入数据源面板

添加数据源

选择数据源

配置数据源

进入管理业页

导入面板

输入面板编号12856后点Load加载

填写基础信息并且选择数据源后点Import导入

