Prometheus 安装和数据采集

81 阅读1分钟

下载和安装

官网下载

image.png

image.png

image.png

数据采集

这里需要下载依赖包

import (
   "fmt"
   "math/rand"
   "net/http"
   "time"

   "github.com/prometheus/client_golang/prometheus"
   "github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
   httpRequestCounter := prometheus.NewCounterVec(
      prometheus.CounterOpts{
         Subsystem: "service",
         Name:      "http_request_total",
         Help:      "Total number of http_request",
      },
      []string{"kind", "api"},
   )
   go func() {
      i := 0
      for {
         if i%2 == 0 {
            m := map[string]string{
               "kind": "user",
               "api":  "/get",
            }
            rand.Seed(time.Now().UnixNano())
            random := rand.Intn(200)
            httpRequestCounter.With(m).Add(float64(random))

            //httpRequestCounter.WithLabelValues("user", "/get").Inc()
         } else {
            m := map[string]string{
               "kind": "order",
               "api":  "/get",
            }
            rand.Seed(time.Now().UnixNano())
            random := rand.Intn(200)
            httpRequestCounter.With(m).Add(float64(random))
         }
         i++
         time.Sleep(time.Second)
      }

   }()

   prometheus.MustRegister(httpRequestCounter)
   http.Handle("/metrics", promhttp.Handler())
   fmt.Println("====================== start metrics =================")
   http.ListenAndServe(":2112", nil)
}

已监测到数据

image.png

prometheus.yml 增加配置

  - job_name: 'test_count'
    metrics_path: /metrics
    static_configs:
      - targets: ['localhost:2112']

搜索service_http_request_total, 面板查看到数据

image.png

image.png