使用 golang 调用 prometheus api 查询指标可以使用以下步骤:
- 安装 prometheus 客户端库
go get github.com/prometheus/client_golang/api
- 创建一个 prometheus 客户端实例
import (
"github.com/prometheus/client_golang/api"
"github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
// 创建一个 prometheus 客户端实例
func newPrometheusClient() (v1.API, error) {
// 设置 prometheus 的地址
config := api.Config{
Address: "http://localhost:9090",
}
client, err := api.NewClient(config)
if err != nil {
return nil, err
}
return v1.NewAPI(client), nil
}
- 使用客户端查询指标
// 查询指标
func queryMetrics(query string) ([]model.SamplePair, error) {
// 创建 prometheus 客户端实例
client, err := newPrometheusClient()
if err != nil {
return nil, err
}
// 执行查询
result, _, err := client.Query(context.Background(), query, time.Now())
if err != nil {
return nil, err
}
// 解析结果
vector := result.(model.Vector)
samples := make([]model.SamplePair, len(vector))
for i, sample := range vector {
samples[i] = sample
}
return samples, nil
}
- 示例使用
// 测试查询
func main() {
samples, err := queryMetrics("up")
if err != nil {
fmt.Println(err)
return
}
for _, s := range samples {
fmt.Printf("name: %s, value: %v\n", s.Metric["instance"], s.Value)
}
}
这样就可以使用 golang 调用 prometheus api 查询指标了。