You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prometheus(搭配Spring Boot)中列出未使用的接口?

问题

我正在维护一个包含大量新旧接口的大型遗留项目,计划删除未使用的旧接口。我们使用Grafana统计接口的调用次数,但Prometheus仅展示至少被调用过一次的接口,未使用的接口不会出现在Grafana中。

现有Prometheus指标示例如下:

# HELP http_server_requests_seconds  
# TYPE http_server_requests_seconds summary
http_server_requests_seconds_count{application="foo",...,uri="/api/internal/v5/foos/{..}/...",} 822.0
http_server_requests_seconds_sum{application="foo",...,uri="/api/internal/v5/foos/{..}/...",} 13.827411282
http_server_requests_seconds_count{application="foo",...,uri="/api/internal/v4/foos/...",} 475.0
http_server_requests_seconds_sum{application="foo",...,uri="/api/internal/v4/foos/...",} 4.885103028
http_server_requests_seconds_count{application="foo",...,uri="/api/ui/...",} 1496.0
http_server_requests_seconds_sum{application="foo",...,uri="/api/ui/...",} 1.638166633
http_server_requests_seconds_count{application="foo",...,uri="/...",} 30589.0
http_server_requests_seconds_sum{application="foo",...,uri="/...",} 23.555870127
http_server_requests_seconds_count{application="foo",...,uri="/api/internal/v5/foos/{..}/...",} 4.0
http_server_requests_seconds_sum{application="foo",...,uri="/api/internal/v5/foos/{..}/...",} 2.474261611
http_server_requests_seconds_count{application="foo",...,uri="/prometheus",} 165998.0
http_server_requests_seconds_sum{application="foo",...,uri="/prometheus",} 1652.047452397

我希望能将未使用的接口也纳入统计,使其显示为:

http_server_requests_seconds_count{application="foo",...,uri="/api/internal/v5/foos/{..}/...",} 0.0
http_server_requests_seconds_count{application="foo",...,uri="/api/internal/v4/foos/...",} 0.0

所有接口历史上都被调用过,但我们最近才添加Prometheus指标,无法获取早期数据。请问该如何实现?

解决方案

方法1:应用初始化时主动上报全量接口的0次指标

  • 从项目路由配置、API文档或代码中提取所有接口的URI列表
  • 在应用启动阶段,遍历这个列表,为每个URI主动推送http_server_requests_seconds_count指标,值设为0.0,同时带上application等对应标签
  • 这种方式能确保所有接口从一开始就有指标存在,后续有调用时会自动累加计数,无需修改监控查询

方法2:在PromQL查询中构造全量接口的0值集合

  • 先整理出所有接口的URI列表,将其构造成静态向量,示例:
    vector(0) * on() group_left(uri) label_replace(vector(1), "uri", "/api/internal/v5/foos/{..}/...", "", "")
    
    把所有接口URI都通过label_replace添加到向量中,形成一个包含所有URI、值为0的指标集合
  • 将这个静态集合和实际的调用计数指标合并,用or操作符:
    http_server_requests_seconds_count or (vector(0) * on() group_left(uri) label_replace(vector(1), "uri", "/api/internal/v5/foos/{..}/...", "", "") or label_replace(vector(1), "uri", "/api/internal/v4/foos/...", "", "") ...)
    
  • 这种方式不用改应用代码,直接在Grafana查询中实现,但接口变动时需要手动更新查询语句

方法3:借助API文档工具同步接口列表生成指标

  • 如果项目用了OpenAPI/Swagger这类API文档工具,定期从文档导出所有接口URI,生成静态指标配置
  • 使用Prometheus的file_sd_configs或者自定义exporter,把这些接口列表转换成0值指标,和应用指标一起被Prometheus采集
  • 这种方式适合接口变动频繁的场景,能自动同步接口列表,减少手动维护量

内容的提问来源于stack exchange,提问作者Edito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:45:44