golang 獲取 prometheus數據

使用github上的一個庫

1.安裝庫

go get github.com/prometheus/client_golang

2.導入

在import中導入,記得要在go.mod中更新一下


Address: "http://xx.xx.xx:9090", 用你的prometheus的地址

result, warnings, err := v1api.Query(ctx, "node_cpu_info{instance=\"computer1\"}", time.Now(), proV1.WithTimeout(15*time.Second)) 這邊的用你的PROMQL查詢語句

可以參考https://prometheus.io/docs/prometheus/latest/querying/api/

Go 复制代码
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/prometheus/client_golang/api"
	proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
	"github.com/prometheus/common/model"
)

var Client api.Client

func init() {
	Client, _ = CreatClient()
}

func CreatClient() (client api.Client, err error) {
	client, err = api.NewClient(api.Config{
		Address: "http://xx.xx.xx:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %v\n", err)
		return nil, err
	}
	return client, nil
}

func Query() (result model.Value, err error) {
	v1api := proV1.NewAPI(Client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	result, warnings, err := v1api.Query(ctx, "node_cpu_info{instance=\"computer1\"}", time.Now(), proV1.WithTimeout(15*time.Second))

	if err != nil {
		return nil, err
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	return result, nil
}


func main() {
	result, err := Label()
	if err != nil {
		fmt.Errorf("%q", err)
	}
	fmt.Printf("Result:\n%v\n", result)
}
相关推荐
jimy12 小时前
C语言模拟对象、方法:“函数指针+结构体“复用函数指针指向的函数体
c语言·开发语言
天外天-亮2 小时前
HBuilder X 使用 uview-plus 方式
开发语言·javascript·hbuilder x·uview-plus
木木子223 小时前
[特殊字符] 音乐播放器——状态驱动的多媒体控制
android·开发语言·华为·php·harmonyos
六个九十度3 小时前
用python脚本访问被网关隔离的嵌入式设备
开发语言·python
酷酷的身影3 小时前
Drivers/LedManager.cs
开发语言·php
小樱花的樱花3 小时前
Linux 线程的创建
linux·c语言·开发语言
xiaoshuaishuai84 小时前
C# AI实现PR处理、单元测试
开发语言·c#·log4j
C++、Java和Python的菜鸟4 小时前
第7章 Java高级技术
java·开发语言
LONGZHIQIN4 小时前
C#基础复习笔记
开发语言·笔记·c#
可靠的仙人掌4 小时前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php