用 Golang、Gin 和 gRPC 配合 Prometheus 打造高性能指标监控系统

| 分类 golang  | 标签 golang  prometheus 

用 Golang、Gin 和 gRPC 配合 Prometheus 打造高性能指标监控系统

本文将带你从零开始在 Go 项目中集成 Prometheus 性能监控,涵盖:

  • 标准 HTTP 服务
  • Gin 框架
  • gRPC 服务
  • 在 Arch Linux、CentOS、Docker 三种环境下安装 Prometheus
  • 如何使用 Prometheus 和 Grafana 查看指标

📦 Golang 中使用 Prometheus 基础集成

安装依赖

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp

示例代码

package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
    httpRequestsTotal = prometheus.NewCounter(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests",
        },
    )
)

func init() {
    prometheus.MustRegister(httpRequestsTotal)
}

func handler(w http.ResponseWriter, r *http.Request) {
    httpRequestsTotal.Inc()
    w.Write([]byte("Hello, Prometheus!"))
}

func main() {
    http.Handle("/metrics", promhttp.Handler())
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

访问:http://localhost:8080/metrics


🚀 在 Gin 中集成 Prometheus

安装中间件

go get github.com/zsais/go-gin-prometheus

示例代码

package main

import (
    "github.com/gin-gonic/gin"
    ginprometheus "github.com/zsais/go-gin-prometheus"
)

func main() {
    r := gin.Default()
    p := ginprometheus.NewPrometheus("gin")
    p.Use(r)

    r.GET("/", func(c *gin.Context) {
        c.String(200, "Hello, Gin!")
    })

    r.Run(":8080")
}

访问:http://localhost:8080/metrics


📡 在 gRPC 中集成 Prometheus

安装依赖

go get github.com/grpc-ecosystem/go-grpc-prometheus

示例代码

package main

import (
    "net"
    "google.golang.org/grpc"
    "github.com/grpc-ecosystem/go-grpc-prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "net/http"
    "log"
    pb "your/proto/package"
)

type server struct {
    pb.UnimplementedYourServiceServer
}

func main() {
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatal(err)
    }

    s := grpc.NewServer(
        grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
    )
    pb.RegisterYourServiceServer(s, &server{})
    grpc_prometheus.Register(s)

    go func() {
        http.Handle("/metrics", promhttp.Handler())
        log.Fatal(http.ListenAndServe(":9094", nil))
    }()

    log.Println("gRPC server listening on :50051")
    s.Serve(lis)
}

访问:http://localhost:9094/metrics


🛠️ 安装 Prometheus

Arch Linux

sudo pacman -S prometheus
sudo systemctl enable --now prometheus.service

访问:http://localhost:9090


CentOS

cd /opt
curl -LO https://github.com/prometheus/prometheus/releases/download/v2.52.0/prometheus-2.52.0.linux-amd64.tar.gz
tar -xvzf prometheus-2.52.0.linux-amd64.tar.gz
mv prometheus-2.52.0.linux-amd64 prometheus

创建 systemd 服务:

[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

[Service]
User=nobody
ExecStart=/opt/prometheus/prometheus \\
  --config.file=/opt/prometheus/prometheus.yml \\
  --storage.tsdb.path=/opt/prometheus/data
Restart=on-failure

[Install]
WantedBy=multi-user.target

启动:

sudo systemctl daemon-reload
sudo systemctl start prometheus
sudo systemctl enable prometheus

Docker

创建 prometheus.yml:

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'go-app'
    static_configs:
      - targets: ['host.docker.internal:8080']
  - job_name: 'grpc-app'
    static_configs:
      - targets: ['host.docker.internal:9094']

启动容器:

docker run -d \\
  -p 9090:9090 \\
  -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \\
  --name prometheus \\
  prom/prometheus

📊 Grafana 可视化(可选)

安装:

docker run -d -p 3000:3000 --name=grafana grafana/grafana

访问 http://localhost:3000,默认账号密码:admin/admin

添加 Prometheus 数据源:http://localhost:9090,开始创建仪表盘。


🔍 如何查看 go-app 的指标

✅ 在 Prometheus 中查看 go-app 指标

  1. 打开 Prometheus 页面:http://localhost:9090
  2. 在搜索框输入:
http_requests_total

或:

rate(http_requests_total[1m])
  1. 点击 “Execute”,再点击 “Graph” 查看图表。

✅ 在 Grafana 中查看 go-app 指标

  1. 登录 Grafana(默认 http://localhost:3000)
  2. 添加数据源:Prometheus,地址 http://localhost:9090
  3. 创建仪表盘 → 添加 Panel
  4. 输入 PromQL 查询语句:
rate(http_requests_total[1m])
  1. 设置图表样式并保存

🎯 常见 Prometheus 指标示例

指标名 说明
http_requests_total 累计的 HTTP 请求总数
rate(http_requests_total[1m]) 最近 1 分钟的平均请求速率
process_resident_memory_bytes 进程占用的内存字节数
go_goroutines 当前 Go 程序运行的 goroutine 数量
go_memstats_heap_alloc_bytes 当前堆分配内存大小

✅ 总结

类型 集成方式
原生 HTTP 使用 promhttp.Handler()
Gin 使用 go-gin-prometheus 中间件
gRPC 使用 go-grpc-prometheus 拦截器
部署方式 支持 Arch Linux / CentOS / Docker 安装
可视化 可通过 Grafana 展示所有指标数据

📁 推荐目录结构

my-monitoring-app/
├── go-http-app/
├── gin-app/
├── grpc-app/
├── prometheus.yml
└── docker-compose.yml  # 可选

📚 参考链接