北冰洋以北 发表于 2025-1-14 05:12:45

Go oom分析(二)——导出dump离线分析

在 Go 步伐中导出内存或 CPU 的 dump 文件(通常通过 pprof 工具生成)并举行分析,以下是详细步调:
1. 在步伐中开启 pprof

在你的 Go 步伐中引入 net/http/pprof,开启 pprof 服务:
import (
    _ "net/http/pprof"
    "log"
    "net/http"
)

func init() {
    go func() {
      log.Println(http.ListenAndServe("localhost:6060", nil))
    }()
}
这样会在 localhost:6060 开启一个 HTTP 服务器,提供调试接口。
2. 导出 Dump 文件

通过访问 pprof 提供的接口,可以导出 CPU、堆内存、Goroutines 等的 dump 文件。
(1)CPU Profile

捕获一段时间的 CPU 使用数据:
curl http://localhost:6060/debug/pprof/profile?seconds=30 -o cpu.prof
默认采样时间是 30 秒,可调解 seconds 参数。
2)Heap (内存分配)

导出当前堆内存分配情况:
curl http://localhost:6060/debug/pprof/heap -o heap.prof

3)Goroutines

导出当前所有 Goroutines 的状态:
curl http://localhost:6060/debug/pprof/goroutine -o goroutine.prof
(4)其他



[*] Block(阻塞分析):
curl http://localhost:6060/debug/pprof/block -o block.prof
注意:需要在步伐中开启阻塞分析:
import "runtime"
func init() {
    runtime.SetBlockProfileRate(1)
}
Mutex(锁分析):
curl http://localhost:6060/debug/pprof/mutex -o mutex.prof
注意:需要开启锁分析:
import "runtime"
func init() {
    runtime.SetMutexProfileFraction(1)
}
3. 分析 Dump 文件

导出的 .prof 文件可以用以下工具分析:
(1)使用 go tool pprof

运行以下命令:
go tool pprof <binary> <dump_file> 例如:
go tool pprof ./your_app
cpu.prof 在交互界面中,常用命令:


[*]top:表现占用资源最多的函数。
[*]list <function>:查看某个函数的详细实现。
[*]web:生成调用图(需要 Graphviz 支持)。
假如是远程服务:
go tool pprof http://localhost:6060/debug/pprof/heap (2)使用火焰图

将 .prof 转为火焰图形式,更直观:


[*]安装 FlameGraph 工具。
[*]导出火焰图:
go tool pprof -svg <binary> <dump_file> > profile.svg


[*]打开生成的 profile.svg 举行查看。
4. 在线分析工具

你也可以将 dump 文件上传到在线分析工具(如 pprof.me)中举行图形化展示。

5. 欣赏器分析

go tool pprof -http=0.0.0.0:8080 ./your_app
heap.prof
5. 示例操纵

假设运行一个 Go 应用:
./your_app
步伐运行中出现内存占用异常,通过以下步调排查:


[*]导出当前堆内存:
curl http://localhost:6060/debug/pprof/heap -o heap.prof



[*]分析 dump 文件:
go tool pprof ./your_app
heap.prof
[*]在交互界面中查看:

[*]top:检查内存占用最大的函数。
[*]web:生成调用图。



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Go oom分析(二)——导出dump离线分析