podman部署使用prometheus+grafana监控spring-boot上报自定义指标
1、安装部署prometheus
和grafana
- 1.1、镜像准备
podman pull docker.io/grafana/grafana:10.0.1
podman pull bitnami/prometheus:2.45.0-debian-11-r0
-
1.2、创建一个本地目录
/data
用于存储数据(目录需要赋读写权限) -
1.3、临时启动一个
prometheus
容器并从中拷贝配置文件prometheus.yml
后停止
podman run --rm --name prometheus bitnami/prometheus:2.45.0-debian-11-r0
打开另外一个命令窗口拷贝文件
podman cp prometheus:/opt/bitnami/prometheus/conf/prometheus.yml /data/prometheus/prometheus.yml
配置文件prometheus.yml
增加scrape_configs
配置如下
scrape_configs:
- job_name: "mixfate-prometheus"
metrics_path: '/actuator/prometheus' # 指标获取路径(由一个spring-boot测试应用提供)
scrape_interval: 5s # 间隔
static_configs:
- targets: ['192.168.1.28:8080'] # 指标实例的地址(默认http协议)
- 1.4、运行
prometheus
podman run -d --rm --name prometheus -p 9090:9090 -v /data/prometheus/prometheus.yml:/opt/bitnami/prometheus/conf/prometheus.yml docker.io/bitnami/prometheus:2.45.0-debian-11-r0
- 1.5、运行
grafana
mkdir /data/grafana
chmod 777 /data/grafana
podman run -d --rm --name grafana -p 3000:3000 -v /data/grafana:/var/lib/grafana docker.io/grafana/grafana:10.0.1
启动后即可通过http://localhost:3000/login
访问,默认用户为和密码为admin
,首次登录提示需要修改密码。
- 1.6、配置数据源
2、spring-boot
上报自定义指标
package com.mixfate.prometheus.monitor;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Random;
@Slf4j
@Component
public class MetricsMonitor {
private Counter orderCount;
private DistributionSummary amountSummary;
private final MeterRegistry registry;
@Autowired
public MetricsMonitor(MeterRegistry registry){
this.registry = registry;
}
@PostConstruct
public void init(){
orderCount = registry.counter("order_count","orderCount","mixfate");
amountSummary = registry.summary("order_amount_sum","orderAmountSum","mixfate");
}
@Scheduled(cron="0/1 * * * * ?")
public void generate(){
log.info("generate");
this.orderCount.increment();
this.amountSummary.record(new Random().nextDouble(100));
}
}