首先集成Prometheus客户端库,再定义Counter、Gauge、Histogram等指标并注册;接着通过HTTP中间件自动收集请求量、延迟等数据;然后暴露/metrics端点供Prometheus抓取;配置prometheus.yml添加抓取任务;最后结合Grafana展示QPS、延迟、错误率等关键指标,并可集成Alertmanager实现告警。

微服务架构下,系统被拆分为多个独立服务,调用链复杂,对可观测性要求更高。Prometheus 作为云原生生态中主流的监控方案,与 Golang 天然契合。通过在 Go 微服务中集成 Prometheus,可以轻松实现指标暴露、采集和告警。下面详细介绍如何使用 Prometheus 监控 Golang 微服务。
要在 Go 项目中启用 Prometheus 监控,首先需要引入官方客户端库:
go get github.com/prometheus/client_golang/prometheus这两个包分别用于定义指标和提供 HTTP 接口供 Prometheus 抓取。
Prometheus 支持 Counter(计数器)、Gauge(仪表盘)、Histogram(直方图)和 Summary(摘要)四种核心指标类型。在微服务中常见用途如下:
立即学习“go语言免费学习笔记(深入)”;
示例代码:
package main
<p>import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)</p><p>var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "endpoint", "code"},
)</p><pre class='brush:php;toolbar:false;'>httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency in seconds.",
Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0},
},
[]string{"method", "endpoint"},
))
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
为了自动收集每个请求的指标,建议使用中间件方式封装处理逻辑。
func metricsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
<pre class='brush:php;toolbar:false;'> // 执行实际处理
next.ServeHTTP(w, r)
// 请求结束后记录指标
method := r.Method
endpoint := r.URL.Path
status := w.(interface{ Status() int }).Status()
httpRequestsTotal.WithLabelValues(method, endpoint, http.StatusText(status)).Inc()
httpRequestDuration.WithLabelValues(method, endpoint).Observe(time.Since(start).Seconds())
}}
注意:若 ResponseWriter 不直接支持 Status(),可包装一个自定义 writer 实现接口。
Prometheus 通过 Pull 模式定期抓取目标的 /metrics 接口。需在服务中添加该路由:
func main() {
http.Handle("/metrics", promhttp.Handler())
<pre class='brush:php;toolbar:false;'>// 示例业务接口
http.HandleFunc("/api/users", metricsMiddleware(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("user list"))
}))
http.ListenAndServe(":8080", nil)}
启动服务后访问 http://localhost:8080/metrics 可查看原始指标数据。
修改 prometheus.yml,添加微服务 job:
scrape_configs:
- job_name: 'go-microservice'
static_configs:
- targets: ['host.docker.internal:8080'] # 若在 Docker 中运行,使用宿主机地址
重启 Prometheus 后,在 Web UI 的 Targets 页面确认状态为 UP,说明抓取正常。
将 Prometheus 添加为数据源后,可导入官方推荐的 Go 监控看板(如 ID: 12683),或创建自定义图表展示 QPS、延迟、错误率等关键指标。
常用查询示例:
rate(http_requests_total[5m])
rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m])
sum(rate(http_requests_total{code!="200"}[5m])) / sum(rate(http_requests_total[5m]))
基本上就这些。只要在服务中正确埋点并暴露指标,Prometheus 就能自动完成采集。结合 Alertmanager 还可设置阈值告警,比如延迟超过 1 秒或错误率突增时通知团队。整个流程简单高效,适合大多数 Golang 微服务场景。
以上就是Golang如何使用Prometheus监控微服务_Golang Prometheus微服务监控实践详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号