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)
}
相关推荐
微学AI2 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡2 小时前
算法日记 - Day3
java·开发语言·算法
Achou.Wang3 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
韭菜炒鸡肝天3 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
Aaron - Wistron3 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102164 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
0566465 小时前
Python康复训练——常用标准库
开发语言·python·学习
骊城英雄5 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
吾儿良辰5 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#
昆曲之源_娄江河畔5 小时前
Python如何安装flask, pymssql
开发语言·python·flask·pymssql