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

如果在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

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站