ZBLOG

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

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

  1. 安装 prometheus 客户端库
  1. go get github.com/prometheus/client_golang/api
  1. 创建一个 prometheus 客户端实例
  1. import (
  2. "github.com/prometheus/client_golang/api"
  3. "github.com/prometheus/client_golang/api/prometheus/v1"
  4. "github.com/prometheus/common/model"
  5. )
  6. // 创建一个 prometheus 客户端实例
  7. func newPrometheusClient() (v1.API, error) {
  8. // 设置 prometheus 的地址
  9. config := api.Config{
  10. Address: "http://localhost:9090",
  11. }
  12. client, err := api.NewClient(config)
  13. if err != nil {
  14. return nil, err
  15. }
  16. return v1.NewAPI(client), nil
  17. }
  1. 使用客户端查询指标
  1. // 查询指标
  2. func queryMetrics(query string) ([]model.SamplePair, error) {
  3. // 创建 prometheus 客户端实例
  4. client, err := newPrometheusClient()
  5. if err != nil {
  6. return nil, err
  7. }
  8. // 执行查询
  9. result, _, err := client.Query(context.Background(), query, time.Now())
  10. if err != nil {
  11. return nil, err
  12. }
  13. // 解析结果
  14. vector := result.(model.Vector)
  15. samples := make([]model.SamplePair, len(vector))
  16. for i, sample := range vector {
  17. samples[i] = sample
  18. }
  19. return samples, nil
  20. }
  1. 示例使用
  1. // 测试查询
  2. func main() {
  3. samples, err := queryMetrics("up")
  4. if err != nil {
  5. fmt.Println(err)
  6. return
  7. }
  8. for _, s := range samples {
  9. fmt.Printf("name: %s, value: %v\n", s.Metric["instance"], s.Value)
  10. }
  11. }

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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?