解锁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等)来展示数据。

      切换 大屏

相关推荐
后端小张9 小时前
基于飞算AI的图书管理系统设计与实现
spring boot
考虑考虑1 天前
Jpa使用union all
java·spring boot·后端
阿杆2 天前
同事嫌参数校验太丑,我直接掏出了更优雅的 SpEL Validator
java·spring boot·后端
昵称为空C2 天前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
麦兜*3 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*3 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
汤姆yu3 天前
基于springboot的毕业旅游一站式定制系统
spring boot·后端·旅游
爱敲代码的TOM3 天前
Prometheus+Grafana构建企业级监控方案
prometheus
计算机毕业设计木哥3 天前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计
hdsoft_huge3 天前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot