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

在Prometheus中添加返回整数列表的自定义指标是否可行?

实现方案说明

首先明确:无法通过Prometheus原生的四种指标类型实现你要的整数列表输出,但可以通过自定义HTTP端点的方式满足需求。

为什么原生指标不行?

Prometheus遵循OpenMetrics规范,要求每个指标样本必须是单个数值(浮点数或整数),Counter、Gauge、Histogram、Summary都是基于单值设计的。你期望的“指标值为整数列表”不符合这个规范,即使手动构造这种返回格式,Prometheus服务器也无法解析和存储这些数据。

可行方案:自定义指标端点

如果你的需求只是对外暴露这些无效ID列表(不需要Prometheus处理),可以在Spring应用中创建一个独立的HTTP端点,专门返回你想要的格式,并且每次请求后清空列表。

示例代码(Spring Boot)

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class InvalidIdsMetricsController {
    // 线程安全的缓存,按错误原因分类存储无效ID
    private final Map<String, List<String>> invalidIdsCache = new ConcurrentHashMap<>();

    // 供业务代码调用,添加无效ID
    public void recordInvalidId(String cause, String id) {
        invalidIdsCache.computeIfAbsent(cause, k -> new ArrayList<>()).add(id);
    }

    // 自定义指标端点
    @GetMapping("/invalid-ids-metrics")
    public String getInvalidIdsMetrics() {
        StringBuilder response = new StringBuilder("# HELP INVALID_IDS\n");
        
        for (Map.Entry<String, List<String>> entry : invalidIdsCache.entrySet()) {
            String cause = entry.getKey();
            List<String> ids = entry.getValue();
            
            if (!ids.isEmpty()) {
                // 构造你要的指标行格式
                response.append(String.format("INVALID_IDS{CAUSE=\"%s\"} %s\n", cause, String.join(", ", ids)));
                // 清空当前分类的ID列表
                ids.clear();
            }
        }
        
        return response.toString();
    }
}

补充说明

  • 这个端点的输出不兼容Prometheus抓取协议,所以Prometheus无法将其作为指标存储。如果需要Prometheus参与处理数据,得换思路:
    • 将每个无效ID转化为单独的指标样本,比如 INVALID_ID{CAUSE="Timeout", ID="978"} 1,用Gauge类型标记(每次抓取后重置为0)。这种方式可以被Prometheus存储,但会生成大量时间序列,需要评估存储成本和性能影响。

内容的提问来源于stack exchange,提问作者pi.314

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:03:32