- runtime/pprof:采集程序(非 Server)的运行数据进行分析,用于可结束的代码块,如一次编解码操作等
- net/http/pprof:采集 HTTP Server 的运行时数据进行分析。用于不可结束的代码块,如 web 应用等
使用场景
分析内存泄漏‘
总结
go中的内存泄露一般都是goroutine泄露,goroutine没有被关闭,或者没有添加超时控制,让goroutine一只处于阻塞状态,不能被GC。
暂时性内存泄漏
- 获取长字符串中的一段导致长字符串未释放
- 获取长slice中的一段导致长slice未释放
- 在长slice新建slice导致泄漏
永久性内存泄漏
- goroutine泄漏
- time.Ticker未关闭导致泄漏
- Finalizer导致泄漏
- Deferring Function Call导致泄漏
常见Pprof使用方式(包net/http/pprof):
1. 网络访问方式 ,go tool 查看火焰图
程序中,单独起一个协程,引入包_ "net/http/pprof" 新监听另一个端口作为pprof访问,如下图方法
func setDebug() error {
if config.C.General.Debug != "" {
port := strings.Split(config.C.General.Debug, ":")[1]
log.WithFields(log.Fields{
"profile": "http://127.0.0.1:" + port + "/debug/pprof/profile",
"goroutines": "http://127.0.0.1:" + port + "/goroutines",
}).Info("open prof debug")
go func() {
http.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
num := strconv.FormatInt(int64(runtime.NumGoroutine()), 10)
w.Write([]byte(num))
})
http.ListenAndServe(config.C.General.Debug, nil)
}()
}
return nil
}
或者直接共用程序监听端口。引入包_ "net/http/pprof"包即可,如下
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
func HelloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world")
}
fun

最低0.47元/天 解锁文章
1103

被折叠的 条评论
为什么被折叠?



