douxi3977 2018-10-30 11:25
浏览 73

循环调用中的Golang内存泄漏

I am running a call to a remote server, as an agent, this call should run every 5 minutes, but in testing, I run it every second. and I see a memory leak, and struggling to resolve it. The Gist of the code is as follows:

 // Set the initial payload to be sent
    payloadBytes, err := json.Marshal(data)
    if err != nil { log.Print("Failed Marshal", err) }
    transport := &http.Transport{ DisableKeepAlives: true }
    client := http.Client{Transport: transport}

    // Repeat the post call to the remote server
    repeatTicker := time.NewTicker(1 * time.Second)
    for {
       select {
       case <- repeatTicker.C:
           body := bytes.NewReader(payloadBytes)
           log.Print("Sending:", string(payloadBytes))
           postCycle(client, body)
       }
    }
    transport.CloseIdleConnections()
  }

func postCycle(client http.Client , body *bytes.Reader){
    resp, err := client.Post("http://mywebsite.io/api", "application/json", body)
    if err != nil { log.Print("Failed to Connect",err) }
    responseData, err := ioutil.ReadAll(resp.Body)
    if err != nil { log.Print("Response contains Errors", err) }
    resp.Body.Close()
}

What I find it, the Transport is opened once and is reused, but the resp.Body.Close() does not seem to have the desired effect, and the memory count continues to rise. The return data is an echo of sent data, so this never changes. Am I missing something glaring here? or will the memory count top out and remain sable when the garbage collection catches up?

  • 写回答

1条回答 默认 最新

  • dqkkrt8860 2018-10-31 08:36
    关注

    Memory leak looked likely, but then after running the routine for a period of time, the memory use settled down, so this is correct for cleaning up objects and not eating up all available memory.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看