对于默认的使用 http.ListenAndServe 的,直接使用
1
| import _ "net/http/pprof"
|
因为 pprof 的 init 方法执行了如下操作
1 2 3 4 5
| http.HandleFunc("/debug/pprof/", Index) http.HandleFunc("/debug/pprof/cmdline", Cmdline) http.HandleFunc("/debug/pprof/profile", Profile) http.HandleFunc("/debug/pprof/symbol", Symbol) http.HandleFunc("/debug/pprof/trace", Trace)
|
如果不是使用 DefaultServeMux(也就是说 http.ListenAndServe 函数的第二个参数不是 nil),可以在路由上使用下方的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| switch name { case "cmdline": pprof.Cmdline(ctx.Response, ctx.Request)
case "profile": pprof.Profile(ctx.Response, ctx.Request)
case "symbol": pprof.Symbol(ctx.Response, ctx.Request)
case "trace": pprof.Trace(ctx.Response, ctx.Request)
default: handler := pprof.Handler(name) handler.ServeHTTP(ctx.Response, ctx.Request) }
|
然后执行 go tool pprof -http=":8081" $host/debug/pprof/profile 即可。
执行该命令后会自动打开浏览器,通过切换 goroutines, heap, profile 可以分别查看 goroutines,堆栈信息和 cpu 占用情况。通过里边的各种图可以比较清晰地发现和排查性能问题。