

新闻资讯
技术学院pprof分析需显式注册、避免全量导入、足够采样时间;日志需透传context以保trace链路完整;gRPC服务端必须监听ctx.Done()实现超时响应。
pprof 抓住 CPU 和内存热点
微服务跑着跑着变慢,第一反应不是加机器,而是看它到底在忙什么。Go 自带的 pprof 是最轻量也最准的切入点,但很多人只开 /debug/pprof 就以为万事大吉。
实际要注意三点:一是必须显式注册到 HTTP mux(默认不自动暴露),二是生产环境别用 net/http/pprof 全量导入(有安全风险),三是采样时间不够长会漏掉偶发抖动。
import _ "net/http/pprof"
// 然后在你的 router 里:
mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))go tool pprof http://localhost:8080/debug/pprof/profile?seconds=30
inuse_space(当前占用)和 alloc_objects(累计分配),go tool pprof -http=:8081 http://localhost:8080/debug/pprof/heap
用 OpenTelemetry 或 Jaeger 做分布式追踪时,经常发现某个 HTTP handler 有 span,但进来的 goroutine 日志里没 trace_id,或者下游调用直接变成新 trace。根本原因不是 SDK 没集成好,而是日志库没接上 context。
标准 log 包完全无视 context;zap 和 zerolog 虽支持字段注入,但不会自动从 context 提取 span context。必须手动透传或用 wrapper。
立即学习“go语言免费学习笔记(深入)”;
otelzap 替代原生 zap:import "go.opentelemetry.io/contrib/zapfield" logger := otelzap.New(zap.Must(zap.NewDevelopment()))
go fn(ctx, ...),而不是裸写 go fn(...))trace_id 字段:如果只有 span_id 没有 trace_id,说明 propagation 失败,大概率是跨 goroutine 时 context 丢了客户端设了 context.WithTimeout,但服务端迟迟不返回,连接却一直 hang 着,甚至触发 TCP keepalive 后才断开。这不是网络问题,而是 gRPC 的 deadline 机制和服务端处理逻辑没对齐。
gRPC 的 timeout 只控制 client-side 的等待,服务端收到请求后是否响应、何时响应、是否做流控,全由服务端自己决定。常见坑是服务端用了 time.Sleep 模拟延迟,或没做 ctx.Done() 监听。
ctx.Done() 并提前退出:func (s *Server) DoSomething(ctx context.Context, req *pb.Request) (*pb.Response, error) {
select {
case <-time.After(5 * time.Second):
return &pb.Response{}, nil
case <-ctx.Done():
return nil, ctx.Err() // 返回 CANCELLED 或 DEADLINE_EXCEEDED
}
}WithTimeout,加上 WithBlock() + FailFast(false) 可缓解重试风暴,但更关键是服务端配合grpcurl 测试时注意加 -plaintext -rpc-timeout 2s,否则默认无超时,看不出问题用 fsnotify + exec.Command 实现配置热重载或二进制热替换后,发现 goroutine 数持续上涨,runtime.NumGoroutine() 从几百涨到几千,但 pprof 的 goroutine profile 里全是 select 或 chan receive,找不到谁在起 goroutine。
本质是旧进程的 goroutine 没被正确清理,尤其是那些监听 channel、timer、signal 的长期运行协程。新进程起来了,老进程的 goroutine 还卡在阻塞原语里,又没被 GC 掉。
ctx.Done() 并退出:go func(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
doWork()
case <-ctx.Done():
return
}
}
}(parentCtx)syscall.Kill(pid, syscall.SIGTERM)),别直接 SIGKILL
go tool pprof -goroutines 对比新旧 profile,重点关注状态为 chan receive 且 stack trace 没有业务函数名的 goroutine —— 很可能就是没监听 cancel 的“幽灵协程”真正难的不是知道这些技巧,而是每次上线前有没有把 pprof 端口、trace 上下文、gRPC 超时策略、goroutine 生命周期这四件事当成 checklist 过一遍。漏掉任意一个,调试成本就翻倍。