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)
}
相关推荐
Smile_2542204181 分钟前
vue3 + ts reactive方式清空表单对象
开发语言·前端·javascript
jjjava2.06 分钟前
Java 多线程核心基础与线程安全
java·开发语言
悟乙己13 分钟前
因果推断方法实践:Python实现合成控制法
开发语言·python
.千余18 分钟前
【C++】C++核心语法:函数重载与缺省参数原理与避坑
c语言·开发语言·c++·经验分享·笔记·git·学习
DreamLife☼22 分钟前
OpenBCI-Python与OpenBCI:实时脑电信号采集实战
开发语言·python·硬件·选型·openbci·cyton·ganglion
AI行业学习24 分钟前
CC-Switch 下载、安装与使用配置指南【2026.5.29】
java·开发语言·vscode·python·eclipse·laravel
许彰午27 分钟前
03_Java流程控制详解
java·开发语言·python
SoftLipaRZC31 分钟前
C语言内存函数完全指南:memcpy/memmove/memset/memcmp
c语言·开发语言
2201_7611990433 分钟前
python运维1
运维·开发语言·python