解锁Spring Boot、Prometheus与Grafana三合一:打造你的专属自定义指标炫酷大屏!

1. 集成Prometheus到Spring Boot

需要在Spring Boot应用中集成Prometheus。可以通过micrometer库来实现。micrometer是一个应用程序监控库,它支持多种监控系统,包括Prometheus。

一招制胜!Spring Boot、Prometheus和Grafana三剑合璧,称霸监控领域!

2. 编写自定义指标

需求: 统计接口访问次数

java 复制代码
/**
 * 功能描述: prometheus:自定义指标
 * 功能需求:
 * 来监控接口请求次数
 * 实际项目项目中,使用AOP,或拦截器方式统计接口的请求信息次数更为优雅
 *
 * @author Songxianyang
 * @date 2024-08-13 10:00
 */
@Slf4j
@RestController
@RequestMapping("/custom-metrics")
@RequiredArgsConstructor
@Api(tags = "自定义指标")
public class CustomMetricsController {
    private final MeterRegistry meterRegistry;

    public static final String METRICS = "metrics.kkxx-poi.request.count";

    /**
     * 详情接口请求统计
     */
    @ApiOperation("详情接口")
    @GetMapping("/get/{id}")
    public String get(@PathVariable("id") String id) {
        Counter.builder(METRICS).tags("apiCode", "get").register(meterRegistry).increment();
        return "详情接口请求统计id:" + id;
    }

    /**
     * 列表接口请求统计
     */
    @ApiOperation("列表接口")
    @PostMapping("/list")
    public String list() {
        Counter.builder(METRICS).tags("apiCode", "list").register(meterRegistry).increment();
        return "列表接口请求统计";
    }
}

可以通过使用AOP来实现自定义指标,可以更优雅地为Spring Boot应用中的方法提供监控支持,并且这些指标可以在Prometheus和Grafana中进行可视化展示。

2. 在Prometheus中调试展示指标

  1. 点击 Graph
  2. 输入 metrics_kkxx_poi_request_count_total 点击 Execute
  1. 点击 Graph

  2. 接口请求次数

4. 在Grafana中展示指标

  1. 创建仪表盘 :

    • 创建一个新的仪表盘(Dashboard)。
    • 添加一个新的面板(Panel)。
    • 在面板的查询部分输入你的自定义指标名称,例如metrics_kkxx_poi_request_count_total
    • 选择一个合适的图表类型(如Graph、Stat等)来展示数据。

      切换 大屏

相关推荐
爱吃羊的老虎7 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
_qingche9 小时前
H2 数据库到 MySQL 数据迁移
java·数据库·spring boot·mysql·spring·重构·kotlin
Peace9 小时前
【Prometheus】
linux·运维·prometheus
码语智行11 小时前
系统启动时初始化数据功能分析
java·spring boot
invicinble11 小时前
推荐一下,遇到的几本比较好的书
spring boot
憧憬成为java架构高手的小白12 小时前
git工作流程简化版
java·spring boot·git
YDS82914 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— 动态决策策略的接口对接
java·spring boot·ai·agent·spring ai·deepseek
淘源码A14 小时前
专科医院云HIS系统源码:技术栈包括SpringBoot、Angular、MySQL等
spring boot·后端·源码·云his·医院信息系统·医院his系统
小马爱打代码14 小时前
基于 SpringBoot 的微服务文件上传下载组件设计与实现
spring boot·后端