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)
}
相关推荐
꧁Q༒ོγ꧂6 小时前
C++ 入门完全指南(四)--函数与模块化编程
开发语言·c++
listhi5206 小时前
对LeNet-5的matlab实现,识别MINST手写数字集
开发语言·matlab
qq_433554546 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
csbysj20206 小时前
Chart.js 饼图:全面解析与实例教程
开发语言
浩瀚地学7 小时前
【Java】常用API(二)
java·开发语言·经验分享·笔记·学习
程序员小寒7 小时前
从一道前端面试题,谈 JS 对象存储特点和运算符执行顺序
开发语言·前端·javascript·面试
七夜zippoe7 小时前
事件驱动架构:构建高并发松耦合系统的Python实战
开发语言·python·架构·eda·事件驱动
古城小栈7 小时前
Rust Trait 敲黑板
开发语言·rust
FL171713148 小时前
MATLAB的Sensitivity Analyzer
开发语言·matlab
lly2024068 小时前
jEasyUI 设置排序指南
开发语言