简介

Prometheus支持很多中配置,如果是多个系统协同运行,通过http接口实现数据同步是最方便的方式。

实现接口

接口要求返回状态码是200HTTP请求头需要包含 Content-Type:application/json

数据格式:列表里面包含多个对象,对象里面有一个targets字段,是一个字符串列表指定监控目标;labels字段是一个map[string]string,设置标签。

[
  {
    "targets": [ "<host>", ... ],
    "labels": {
      "<labelname>": "<labelvalue>", ...
    }
  },
  ...
]
// main.go
package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 配置对象
type Object struct {
	Targets []string          `json:"targets"`
	Labels  map[string]string `json:"labels"`
}

func main() {
	log.Println("start...")
	r := gin.Default()
	r.GET("/prom/node_exporter", func(c *gin.Context) {
		objs := []Object{
			{
				Targets: []string{"localhost:9100", "192.168.122.1:9100"},
				Labels:  map[string]string{"env": "testing"},
			},
		}
		c.JSON(http.StatusOK, objs)
	})
	r.Run(":8088")
}
# 编译
go mod init promserver
go mod tidy -v 
go build  main.go -p promserver

prometheus配置

配置scrape_configs,加上对应的job

...
  - job_name: "node_exporter"
    http_sd_configs:
      - url: http://localhost:8088/prom/servers
...
# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "node_exporter"
    http_sd_configs:
      - url: http://localhost:8088/prom/servers

总结

重载配置文件之后,每分钟自动请求接口获取数据。