使用 prometheus 中间件统计不同路由的 qps 指标。在 go-zero 的服务配置文件中引入 prometheus 并设置 path,框架会自动为每个路由生成 http_request_duration_seconds_count 等指标,通过 handler 标签区分具体路径。

prometheus 中间件如何配置以暴露指标
在 etc/xxx.yaml 中配置 prometheus 节点即可生效。核心是设置 path 参数,指定 Prometheus 抓取指标的 HTTP 端点。默认情况下,go-zero 会基于 net/http 的 Handler 拦截请求,自动记录请求次数、耗时和状态码。

// main.go
package main
import (
"flag"
"log"
"net/http"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/config.yaml", "config file")
func main() {
flag.Parse()
var c rest.RestConf
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
handler := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
server.AddRoutes([]rest.Route{
{
Method: http.MethodGet,
Path: "/api/hello",
Handler: handler,
},
})
log.Printf("Starting server at %s:%d\n", c.Host, c.Port)
server.Start()
}
对应的 etc/config.yaml 内容如下:
Name: hello Host: 0.0.0.0 Port: 8888 Prometheus: Host: 0.0.0.0 Port: 9091 Path: /metrics
启动服务后,访问 http://localhost:9091/metrics 即可看到类似以下的指标:
# HELP http_request_duration_seconds_count The http request duration histogram in seconds.
# TYPE http_request_duration_seconds_count counter
http_request_duration_seconds_count{handler="/api/hello",method="GET",status="200"} 1
如何验证特定路由的 QPS 数据是否正确上报
通过编写一个简单的测试用例或手动发送请求,观察 /metrics 输出中对应 handler 标签的值变化。确保 go-zero 的 prometheus 中间件已正确挂载到 RestServer 上。

// test_prometheus_test.go
package main
import (
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPrometheusMetrics(t *testing.T) {
// 假设服务已在后台运行,或者使用 httptest.NewServer
resp, err := http.Get("http://localhost:8888/api/hello")
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
io.ReadAll(resp.Body)
resp.Body.Close()
// 等待一小段时间让指标刷新(可选,通常即时可见)
time.Sleep(100 * time.Millisecond)
// 获取 metrics
metricsResp, err := http.Get("http://localhost:9091/metrics")
assert.NoError(t, err)
body, _ := io.ReadAll(metricsResp.Body)
metricsResp.Body.Close()
// 检查是否包含正确的 handler 标签
assert.True(t, strings.Contains(string(body), `handler="/api/hello"`))
assert.True(t, strings.Contains(string(body), `method="GET"`))
assert.True(t, strings.Contains(string(body), `status="200"`))
}
handler 标签中的路径格式是如何确定的
go-zero 默认使用注册路由时的 Path 作为 handler 标签的值。如果使用了动态参数(如 /api/user/:id),默认行为可能会将路径标准化或保留原始路径,具体取决于版本和配置。通常建议在使用动态路由时,注意监控指标中的路径聚合情况,避免产生过多的唯一指标键。



















