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

如何从WebAPI向远程Prometheus发送自定义指标?

解决方案:无需自建Prometheus,直接推送数据到remote_write端点

你不需要自建Prometheus实例,有几种直接的方式把你的队列数据转换成Prometheus兼容格式并发送到目标remote_write端点:

1. 直接构造remote_write请求(代码/脚本实现)

Prometheus的remote_write协议支持JSON或Protobuf格式的HTTP POST请求,你可以在WebAPI处理数据时,直接把数据转换成符合格式的请求体,发送到对方的/api/v1/write端点。

格式说明

每个数据点需要转换成Prometheus的TimeSeries结构,包含:

  • 指标名称:比如自定义为app_queue_backlog
  • 标签:把你的Name、Protocol作为标签(方便对方聚合查询)
  • 样本值:Count作为数值,TimeStamp转成毫秒级Unix时间戳

示例请求(JSON格式)

假设对方的remote_write地址是http://target-prometheus:9090/api/v1/write,用curl发送的示例:

curl -X POST http://target-prometheus:9090/api/v1/write \
  -H "Content-Type: application/json" \
  -d '{
    "timeseries": [
      {
        "labels": [
          {"name": "__name__", "value": "app_queue_backlog"},
          {"name": "app_name", "value": "App1 Queue"},
          {"name": "protocol", "value": "AMQP"}
        ],
        "samples": [
          {"value": 53, "timestamp": 1699969383000}
        ]
      }
    ]
  }'

你可以在WebAPI的代码里(比如Python、Java等)封装这个逻辑,每次收到数据后同步发送请求。

2. 使用Telegraf作为中转适配

Telegraf是轻量级的数据收集代理,支持将自定义数据转换成Prometheus指标,并直接发送到remote_write端点。

配置步骤

  1. 安装Telegraf后,修改配置文件telegraf.conf:
    • 输入插件:用exec插件从数据库拉取数据(或直接读取WebAPI的输出),输出格式为InfluxDB Line Protocol(方便转换)
    • 输出插件:启用prometheus_remote_write,配置目标端点地址

示例配置片段

# 输入:从脚本读取数据库中的队列数据,输出Line Protocol格式
[[inputs.exec]]
  commands = ["python3 /path/to/fetch_queue_data.py"]
  data_format = "influx"

# 输出:发送到目标Prometheus的remote_write端点
[[outputs.prometheus_remote_write]]
  urls = ["http://target-prometheus:9090/api/v1/write"]

fetch_queue_data.py的作用是从数据库查询数据,输出类似:

app_queue_backlog,app_name="App1 Queue",protocol="AMQP" count=53 1699969383000

3. 备选:使用Pushgateway(适合临时/短周期任务)

如果对方的Prometheus配置了拉取Pushgateway的规则,你可以把数据推到Pushgateway,由对方Prometheus主动拉取。但注意Pushgateway不会自动过期数据,适合短生命周期的任务队列数据,长期指标建议用前两种方式。

示例推送命令

echo "app_queue_backlog{app_name=\"App1 Queue\",protocol=\"AMQP\"} 53 $(date +%s000)" | curl --data-binary @- http://pushgateway:9091/metrics/job/queue_backlogs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:35:16