doumei1772 2018-10-19 10:15
浏览 1428
已采纳

如果在Golang http传输中保持连接的连接数达到MaxIdleConns,会发生什么情况

I have some questions when using http.Transport to setup http client

Assume we have MaxIdleConns=10, MaxIdleConnsPerHost=2, five different hosts each of which has two keep-live connections and that means the number of connections reach MaxIdleConns.

  1. What will client do when a new connection whose target host maybe one of the five hosts is needed?
  2. What will client do when a new different host connection is needed?

By the way, if I have an server using http.ListenAndServe, how to configure it, like when to close keep-live connections? I would be grateful if there were any example codes.

  • 写回答

1条回答 默认 最新

  • dongmin4990 2018-10-19 13:50
    关注

    If you are using the default Go HTTP client, it will throw an error "too many open files error" when you reach the maximum connection limit during high frequency API calls. This happens because, the default HTTP client won't close the connections once created. In order to solve this issue, you have to create a custom HTTP client and set a timeout interval.

    var netTransport = &http.Transport{
      Dial: (&net.Dialer{
        Timeout: 5 * time.Second,
      }).Dial,
      TLSHandshakeTimeout: 5 * time.Second,
    }
    var netClient = &http.Client{
      Timeout: time.Second * 10,
      Transport: netTransport,
    }
    response, _ := netClient.Get(url)
    

    Refer this link for more details, refer this link https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?