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 服务:
  1. import (
  2.     _ "net/http/pprof"
  3.     "log"
  4.     "net/http"
  5. )
  6. func init() {
  7.     go func() {
  8.         log.Println(http.ListenAndServe("localhost:6060", nil))
  9.     }()
  10. }
复制代码
这样会在 localhost:6060 开启一个 HTTP 服务器,提供调试接口。
2. 导出 Dump 文件

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

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

导出当前堆内存分配情况:
  1. curl http://localhost:6060/debug/pprof/heap -o heap.prof
复制代码
3)Goroutines

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


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

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

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

假如是远程服务:
  1. go tool pprof http://localhost:6060/debug/pprof/heap
复制代码
(2)使用火焰图

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

  1. go tool pprof -svg <binary> <dump_file> > profile.svg
复制代码

4. 在线分析工具

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

5. 欣赏器分析

  1. go tool pprof -http=0.0.0.0:8080 ./your_app
  2. heap.prof
复制代码

5. 示例操纵

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

  1. curl http://localhost:6060/debug/pprof/heap -o heap.prof
复制代码

  1. go tool pprof ./your_app
  2. heap.prof
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4