douyin9987 2019-08-27 22:55
浏览 427

关闭Go http.Client的连接池

For testing purposes I'm trying to create a net/http.Client in Go that has connection pooling disabled. What I'm trying to achieve is a new TCP connection is established to the address on every HTTP/1.x request.

Currently I have:

        c = &http.Client{
            Transport: &http.Transport{
                DialContext: (&net.Dialer{
                    Timeout:   5 * time.Second,
                    KeepAlive: 5 * time.Second,
                }).DialContext,
                TLSHandshakeTimeout:   5 * time.Second,
                ResponseHeaderTimeout: 5 * time.Second,
                ExpectContinueTimeout: 1 * time.Second,
            },
        }

Any ideas how should I tweak this?

I'm seeing that if I set c.Transport.MaxIdleConns = 1 this could work, but I'm not exactly sure if this still allows 1 in-use + 1 idle (2 total) TCP connections:

    // MaxIdleConns controls the maximum number of idle (keep-alive)
    // connections across all hosts. Zero means no limit.
    MaxIdleConns int

Similarly, it seems like c.Dialer.KeepAlive = -1 could do this, too:

    // KeepAlive specifies the keep-alive period for an active
    // network connection.
    // If zero, keep-alives are enabled if supported by the protocol
    // and operating system. Network protocols or operating systems
    // that do not support keep-alives ignore this field.
    // If negative, keep-alives are disabled.

but I'm not sure about the behavior for TCP connections + Keep-Alive + HTTP.

Another approach is to try to kill idle TCP connections as soon as possible, so I set c.Transport.IdleConnTimeout = 1*time.Nanosecond.

When I did this, my Client.Do() now occassionally returns error:

tls: use of closed connection

I'm suspecting this is a Go stdlib issue (perhaps a race) that it uses a connection that should've been taken out of a pool.

  • 写回答

1条回答 默认 最新

  • drsqpko5286 2019-08-27 23:51
    关注

    The http.Transport has a property called MaxConnsPerHost

    MaxConnsPerHost optionally limits the total number of connections per host, including connections in the dialing, active, and idle states.

    It includes the dialing, active and idle states

    评论

报告相同问题?

悬赏问题

  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义