此程序的主要功能是將文件中數據導入到clickhouse數據庫中。java
服務器內存每隔一段時間會耗盡
golang
因爲使用的是go語言開發的,因此採用了業界流行的工具pprof。
sql
參考URL:https://cizixs.com/2017/09/11/profiling-golang-program/
1 //引用pprof
2 import "net/http"
3 import_ "net/http/pprof"
4
5 //在主函數中新增端口監控程序
6 //因爲個人代碼原本就是守護進程,因此這裏採用新開一個監聽協程方式,防止阻塞
7 func main(){
8 go func(){
9 http.ListenAndServe("0.0.0.0:80", nil)
10 }()
11 //其餘代碼
12 ...
13 }
2)在服務器上安裝 golang pprof 程序,進行數據採集。
數據庫
安裝方法:yum install golang pprof
3)使用命令對heap進行dump分析,這個工具的好處是dump後能夠直接生成pdf或png
c#
1 [root@centos ~]# go tool pprof /root/clickhouse_runner/clickhouse_mssql_e
tl http://0.0.0.0:80/debug/pprof/heap
2 Fetching profile over HTTP from http://0.0.0.0:80/debug/pprof/heap
3 Saved profile in /root/pprof/pprof.clickhouse_mssql_etl.alloc_objects.all
oc_space.inuse_objects.inuse_space.012.pb.gz
4 File: clickhouse_mssql_etl
5 Type: inuse_space
6 Time: Feb 5, 2020 at 4:15pm (CST)
7 Entering interactive mode (type "help" for commands, "o" for options)
8 (pprof) pdf
9 Generating report in profile003.pdf
10 (pprof) quit
11 [root@centos ~]
4)找到內存泄漏的源頭,開始修改代碼
修改前源代碼:
centos
1 connect, err := sql.Open("clickhouse", connstring)
2 if err != nil {
3 return err
4 }
5 load_start := time.Now()
6 tx, err := connect.Begin()
7 if err != nil {
8 log.Println(full_filename, "begin err", err)
9 return err
10 }
11 stmt, err := tx.Prepare("insert ... values....")
12 if err != nil {
13 log.Println(full_filename, "preare err", err)
14 return err
15 }
16 _, er := stmt.Exec(...)
17 if er != nil {
18 log.Println("err", er)
19 }
20 er2 := tx.Commit()
21 if er2 != nil {
22 log.Println(db_view, "err", er2)
23 }
24 stmt.Close()
25 connect.Close()
1 func (stmt *stmt) Close() error {
2 stmt.ch.logf("[stmt] close")
3 //新增再次回收內存數據
4 if stmt.ch.block != nil {
5 stmt.ch.block.Reset()
6 }
7 return nil
8 }
b. 直接釋放stmt的對象,利用gc 的自動回收(考慮後仍是採用這個方式更合理些)
服務器
1 stmt.Close()
2 connect.Close()
3 //新增直接將stmt,connect對象置nil
4 //clear mem
5 stmt = nil
6 tx = nil
7 connect = nil
1 connect, err := sql.Open("clickhouse", connstring)
2 if err != nil {
3 return err
4 }
5 load_start := time.Now()
6 tx, err := connect.Begin()
7 if err != nil {
8 log.Println(full_filename, "begin err", err)
9 return err
10 }
11 stmt, err := tx.Prepare("insert ... values....")
12 if err != nil {
13 log.Println(full_filename, "preare err", err)
14 return err
15 }
16 _, er := stmt.Exec(...)
17 if er != nil {
18 log.Println("err", er)
19 }
20 er2 := tx.Commit()
21 if er2 != nil {
22 log.Println(db_view, "err", er2)
23 }
24 stmt.Close()
25 connect.Close()
26
27 //***** clear mem for gc ******
28 stmt = nil
29 tx = nil
30 connect = nil
31 //////////////////////////////////////////////////////////////////////////////////
5) 發佈修改後的代碼,進行觀察,經過觀察發現系統內存能夠正常回收與釋放
函數
通過本次golang的調試發生,真正的緣由是gc內存釋放不夠及時,存在滯後性(經過其餘服務器觀察發現,當壓力小的時候,內存是能夠正常釋放的)。
因此最佳實踐仍是,在涉及到golang中使用大對象或者頻繁建立內存的時候,要採用將對象設置能obj = nil 的方式,告知gc 我已經確實再也不使用該內存塊了,以便gc快速的回收,減小迭代gc。
另外,這種方式是能夠應用到如java,c# 等語言身上的,它們都存在相似的問題。工具