对于默认的使用 http.ListenAndServe 的,直接使用
import _ "net/http/pprof"因为 pprof 的 init 方法执行了如下操作
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),可以在路由上使用下方的代码。
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 占用情况。通过里边的各种图可以比较清晰地发现和排查性能问题。
暂时没有留言