最近用golang开发了一个socket服务端,主要逻辑就是接收客户端发来的数据解析后存入opentsdb中,但是跑一段时间后发现内存就会增长,而且不会被gc回收,初步判定是由于大量make[]byte导致内存不释放,代码如下,求高人解惑?funcStartTCP()error{tcp_addr,_:=net.ResolveTCPAddr("tcp4",tcp_listen)listener,err:=net.ListenTCP("tcp4",tcp_addr)iferr!=nil{returnerr}deferlistener.Close()log.Info("starttcplistenon%s",tcp_listen)for{conn,err:=listener.AcceptTCP()iferr!=nil{log.Error("accepterror%s",err.Error())continue}log.Info("newsessioncreate%s",conn.RemoteAddr().String())goHandlerConn(conn)}}funcReadPacket(conn*net.TCPConn)[]byte{head:=make([]byte,4)_,err:=io.ReadFull(conn,head)iferr!=nil{returnnil}size:=binary.BigEndian.Uint32(head)data:=make([]byte,size)_,err=io.ReadFull(conn,data)iferr!=nil{returnnil}returndata}funcHandlerConn(conn*net.TCPConn){addr:=conn.RemoteAddr().String()deferfunc(){iferr:=conn.Close();err!=nil{log.Error("closesessionerror%s",err.Error())}else{log.Info("sessionclosed%s",addr)}}()for{data:=ReadPacket(conn)iflen(data)==0{log.Warn("emptydata")return}goHandlerMsg(conn,data,t)}}附pprof信息(pprof)top9.92GBof9.93GBtotal(100%)Dropped359nodes(cum<=0.05GB)flatflat%sum%cumcum%9.92GB100%100%9.92GB100%main.ReadPacket00%100%9.92GB100%main.HandlerConn00%100%9.92GB100%runtime.goexit(pprof)listmain.ReadPacketTotal:9.93GBROUTINE========================main.ReadPacketin/tmp/td-server/tcp_server.go9.92GB9.92GB(flat,cum)100%ofTotal..30:goHandlerConn(conn)..31:}..32:}..33:..34:funcReadPacket(conn*net.TCPConn)[]byte{..35:head:=make([]byte,4)..36:_,err:=io.ReadFull(conn,head)..37:iferr!=nil{..38:returnnil..39:}..40:size:=binary.BigEndian.Uint32(head)9.92GB9.92GB41:data:=make([]byte,size)..42:_,err=io.ReadFull(conn,data)..43:iferr!=nil{..44:returnnil..45:}..46:returndata..47:}
www说
相关分类