Prometheus监控jvm指标
重点在于接入应用完成监控指标,默认已有Prometheus和grafana环境,如有需要安装Prometheus和grafana请搜索详细的安装方式
一、springboot应用接入
1.1 添加依赖
注意,这里不需要加版本号,跟随springboot的父版本即可
<!-- spring-boot-actuator依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- prometheus依赖 -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>1.2 修改端点配置
springboot的yaml文件添加一下配置,开启Prometheus的指标采集
# 开启健康检查
management:
# 自定义管理服务地址和端口,默认和应用程序地址端口一致
server:
port: 8081
endpoint:
shutdown:
enabled: true
health:
show-details: always
endpoints:
web:
exposure:
# 开启端点,*表示开启所有
include:
- prometheus
metrics:
# 指标采集标签名
tags:
application: ${spring.application.name}
# 启用对接prometheus服务采集指标数据
prometheus:
metrics:
export:
enabled: true三、二进制或docker安装的k8s获取指标
在prometheus.yml文件的【scrape_configs】中增加监控配置,并且重启
**重点:**targets后面的地址是应用的地址,job_name表示任务名称
scrape_configs:
- job_name: "springboot-application"
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ["127.0.0.1:8081"]四、基于kube-Prometheus获取指标
4.1 添加service
应用需要暴露监控指标的端口发布到service当中
---
apiVersion: v1
kind: Service
metadata:
annotations: {}
labels:
k8s.name: metrics
name: test
namespace: test
spec:
ports:
- name: metrics
port: 8081
protocol: TCP
targetPort: 8081
selector:
k8s.name: application-name
sessionAffinity: None
type: ClusterIP4.2 添加ServiceMonitor
什么是ServiceMonitor:ServiceMonitor 是一个自定义资源,用于指定如何监控 Kubernetes 服务。它定义了要监控的服务、端口和相关的指标抓取配置, 使 Prometheus 能够自动发现并抓取这些服务的指标数据。这简化了监控配置的过程,确保监控系统能够动态响应集群中的变化。
执行完一下内容以后,重启Prometheus-k8s服务
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: monitor
namespace: test
spec:
# 指定监控后端目标的策略
endpoints:
# 监控数据抓取的时间间隔
- interval: 15s
# 指定metrics端口,注意是端口名称不是端口号
port: metrics
# Metrics接口路径
path: /actuator/prometheus
# 监控目标Service所在的命名空间
namespaceSelector:
matchNames:
- test
# 监控目标Service目标的标签。
selector:
matchLabels:
k8s.name: metrics4.3 Prometheus-k8s读取权限的问题
修改Prometheus-k8s的集群权限
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
labels:
app.kubernetes.io/component: prometheus
app.kubernetes.io/name: prometheus
app.kubernetes.io/part-of: kube-prometheus
app.kubernetes.io/version: 2.29.1
name: prometheus-k8s
rules:
- apiGroups:
- ""
resources:
- nodes/metrics
- services
- endpoints
- pods
verbs:
- get
- list
- watch
- nonResourceURLs:
- /metrics
verbs:
- get五、grafana添加仪表盘
官网搜索JVM仪表信息,挑选自己合适的仪表盘

复制仪表盘的id或者下载json,如果服务器有互联网权限的情况下复制id,没有的话下载json导入。

打开自己的grafana控制台,选择仪表盘

导入仪表盘,最后保存即可


