答案:通过中间件记录请求路径、耗时和状态码,结合原子操作统计请求数与错误数,使用Prometheus客户端库注册指标并暴露/metrics接口,实现请求监控与可视化分析。

在Go语言开发中,实现简单的请求统计与监控可以帮助我们了解服务的运行状态,比如每秒请求数、响应时间、错误率等。这类功能不需要引入复杂的监控系统也能快速落地,尤其适合中小型项目或初期阶段的服务。
最直接的方式是在HTTP服务中通过中间件来收集每个请求的信息。Go的net/http包支持中间件模式,可以在不修改业务逻辑的前提下完成数据采集。
定义一个简单的中间件,记录请求路径、耗时、状态码:
func MetricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;"> // 使用包装的ResponseWriter捕获状态码
rw := &responseWriter{ResponseWriter: w, statusCode: 200}
next.ServeHTTP(rw, r)
duration := time.Since(start)
// 打印日志或发送到指标系统
log.Printf("method=%s path=%s status=%d duration=%v",
r.Method, r.URL.Path, rw.statusCode, duration)
// 可以在这里累计指标:如QPS、延迟分布等
recordRequest(r.URL.Path, duration, rw.statusCode)
})}
立即学习“go语言免费学习笔记(深入)”;
type responseWriter struct { http.ResponseWriter statusCode int }
func (rw *responseWriter) WriteHeader(code int) { rw.statusCode = code rw.ResponseWriter.WriteHeader(code) }
这个中间件可以嵌入到任何标准的http.Handle或http.HandleFunc之前,例如:
http.Handle("/api/", MetricsMiddleware(http.HandlerFunc(apiHandler)))
如果只是想统计总请求数、成功/失败次数,可以用sync.Atomic操作保证并发安全。
示例:统计总请求数和错误数
var (
totalRequests int64
errorRequests int64
)
<p>func incrementTotal() {
atomic.AddInt64(&totalRequests, 1)
}</p><p>func incrementError() {
atomic.AddInt64(&errorRequests, 1)
}</p><p>// 暴露一个/metrics接口输出当前数据
func metricsHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "total_requests %d\n", atomic.LoadInt64(&totalRequests))
fmt.Fprintf(w, "error_requests %d\n", atomic.LoadInt64(&errorRequests))
}
将metricsHandler注册为/metrics路由,就可以用curl或Prometheus抓取。
虽然上面的方法能记录数据,但要图形化展示还需要更规范的格式。Prometheus是常用的开源监控系统,Go官方提供了客户端库prometheus/client_golang。
步骤如下:
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"path", "method", "status"},
)
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Histogram of request latencies.",
Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0},
},
[]string{"path"},
))
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
在中间件中更新这些指标:
httpRequestsTotal.WithLabelValues(r.URL.Path, r.Method, fmt.Sprintf("%d", rw.statusCode)).Inc()
httpRequestDuration.WithLabelValues(r.URL.Path).Observe(duration.Seconds())
然后暴露Prometheus标准接口:
http.Handle("/metrics", promhttp.Handler())
启动服务后,访问/metrics即可看到符合Prometheus格式的数据,可用于Grafana展示或Alertmanager告警。
除了暴露指标接口,也可以每隔一段时间打印一次统计摘要,便于本地调试。
例如每10秒输出一次QPS和平均延迟:
go func() {
ticker := time.NewTicker(10 * time.Second)
var lastCount int64
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for range ticker.C {
current := atomic.LoadInt64(&totalRequests)
qps := (current - lastCount) / 10
log.Printf("QPS: %d, Total Requests: %d", qps, current)
lastCount = current
}}()
这种方式轻量,适合资源受限环境。
基本上就这些。从中间件采集、原子计数到对接Prometheus,你可以根据项目复杂度选择合适方案。核心思路是:拦截请求 → 记录数据 → 暴露出口 → 可视化分析。不复杂但容易忽略的是并发安全和指标命名规范。
以上就是如何在Golang中实现简单的请求统计与监控_Golang请求统计监控项目实战汇总的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号