Mystery0の小站

Mystery0の小站

SpringBoot项目上报JVM指标数据到Nightingale

SpringBoot项目上报JVM指标数据到Nightingale

SpringBoot指标暴露

通过 spring-boot-starter-actuator 组件暴露endpoint,然后通过 micrometer-registry-prometheus 暴露Prometheus接口,详情请查阅其他文章,有很多的,这里就不细讲了。

Categraf部署到Pod中

前置条件:SpringBoot项目本地启动之后,可以通过 http://localhost:8080/actuator/prometheus 获取到指标数据 此处直接在现有Pod中添加一个Categraf容器,用于采集Prometheus的数据

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{PROJECT_NAME}}-deployment
  namespace: server
spec:
  selector:
    matchLabels:
      app: {{PROJECT_NAME}}
  template:
    metadata:
      labels:
        app: {{PROJECT_NAME}}
    spec:
      containers:
        - ...//业务容器
        - name: categraf
          image: flashcatcloud/categraf:latest
          imagePullPolicy: Always
          env:
            - name: TZ //添加时区配置,Categraf打印的日志就会是正常的时区
              value: Asia/Shanghai
            - name: APP_NAME //此处自定义了一个环境变量APP_NAME
              value: {{PROJECT_NAME}}
          volumeMounts:
            - name: categraf-config
              mountPath: /etc/categraf/conf/config.toml
              subPath: config.toml
            - name: config-storage
              mountPath: /etc/categraf/conf/input.prometheus/prometheus.toml //挂载Prometheus采集配置文件
              subPath: prometheus.toml
      volumes:
        - name: categraf-config
          configMap:
            name: categraf-config
        - name: config-storage
          configMap:
            name: {{PROJECT_CONFIG_NAME}}
        - name: log-storage
          emptyDir: {}

添加一个时区,用于日志中时间的时区调整。 自定义了环境变量 APP_NAME ,然后就是把ConfigMap中的Prometheus采集配置文件挂载到正确的位置。

下面是采集器的config.toml,里面使用到了 APP_NAME 这个环境变量。

[global]
print_configs = false

# 让上报的ident字段为服务名称,这样在多个副本时可以将指标合并起来展示和处理
hostname = "$APP_NAME"

omit_hostname = false

# 往下省略其他配置

然后就是大头的Prometheus采集配置文件

[[instances]]
urls = ["http://$HOSTNAME:8080/actuator/prometheus"]
url_label_value = "{{.Hostname}}"

注意:我们这里把HOSTNAME环境变量(默认是pod名称)塞到了链接中的Hostname部分,然后通过从categraf的特殊配置 url_label_value 再从url中取出来,这样子我们就完成了服务多个副本的合并以及pod的区分。

最终效果截图: image

最后是要做啥我就不多说了吧,指标上面已经可以合并或者区分了。