场景
在一台服务器中运行了多个服务,在运行一段时间后(不足一天),发现某个进程占用了50%以上的内存资源,导致服务器异常
解决方案
首先在代码中开启pprof性能分析
runtime.SetBlockProfileRate(1)
go func() {
log.Println(http.ListenAndServe(":9080", nil))
}()
采用在web界面查看的方式,此处监听9080端口
打开浏览器访问web页面:http://ip:1080/debug/pprof/访问
/debug/pprof/
Types of profiles available:
Count Profile
4320 allocs
265 block
0 cmdline
110 goroutine
4320 heap
0 mutex
0 profile
48 threadcreate
0 trace
full goroutine stack dump
Profile Descriptions:
allocs: A sampling of all past memory allocations
block: Stack traces that led to blocking on synchronization primitives
cmdline: The command line invocation of the current program
goroutine: Stack traces of all current goroutines
heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.
mutex: Stack traces of holders of contended mutexes
profile: CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.
threadcreate: Stack traces that led to the creation of new OS threads
trace: A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.
讲到内存泄漏,第一反应是去查看heap,实际上在查看时
heap profile: 718: 76326576 [829493: 1114177328] @ heap/1048576
1: 75759616 [1: 75759616] @ 0x40f2f9 0x410dc9 0x4143aa 0x685cee 0x686045 0x6ad612 0x6ad345 0xab8dca 0xab8da3 0x9cf4fc 0x99a1e9 0x9cf6bb 0x667b4c 0x99bd85 0x9b9eb3 0x7dbf03 0x7d742d 0x471801
# 0x685ced github.com/gogf/gf