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)
}
相关推荐
花酒锄作田11 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理11 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12311 天前
matlab画图工具
开发语言·matlab
dustcell.11 天前
haproxy七层代理
java·开发语言·前端
norlan_jame11 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone11 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549611 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月11 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371711 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian11 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript