ZBLOG

使用 golang 如何调用 prometheus api 查询指标?

使用 golang 调用 prometheus api 查询指标可以使用以下步骤:

  1. 安装 prometheus 客户端库
go get github.com/prometheus/client_golang/api
  1. 创建一个 prometheus 客户端实例
import (
  "github.com/prometheus/client_golang/api"
  "github.com/prometheus/client_golang/api/prometheus/v1"
  "github.com/prometheus/common/model"
)

// 创建一个 prometheus 客户端实例
func newPrometheusClient() (v1.API, error) {
  // 设置 prometheus 的地址
  config := api.Config{
    Address: "http://localhost:9090",
  }

  client, err := api.NewClient(config)
  if err != nil {
    return nil, err
  }

  return v1.NewAPI(client), nil
}
  1. 使用客户端查询指标
// 查询指标
func queryMetrics(query string) ([]model.SamplePair, error) {
  // 创建 prometheus 客户端实例
  client, err := newPrometheusClient()
  if err != nil {
    return nil, err
  }

  // 执行查询
  result, _, err := client.Query(context.Background(), query, time.Now())
  if err != nil {
    return nil, err
  }

  // 解析结果
  vector := result.(model.Vector)
  samples := make([]model.SamplePair, len(vector))
  for i, sample := range vector {
    samples[i] = sample
  }

  return samples, nil
}
  1. 示例使用
// 测试查询
func main() {
  samples, err := queryMetrics("up")
  if err != nil {
    fmt.Println(err)
    return
  }

  for _, s := range samples {
    fmt.Printf("name: %s, value: %v\n", s.Metric["instance"], s.Value)
  }
}

这样就可以使用 golang 调用 prometheus api 查询指标了。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1626

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?