IT评测·应用市场-qidao123.com
标题:
Go oom分析(二)——导出dump离线分析
[打印本页]
作者:
北冰洋以北
时间:
2025-1-14 05:12
标题:
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企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4