donjd86266 2019-03-30 00:58
浏览 171

如何在Go中缓存/重用TLS连接

I've run into a problem where I create a new connection each request and it is terribly inefficient.

I would like to allow a set maximum number of TLS connections to stay open/cached on my client at once. When data is ready to be transmitted it first checks if there is an idle connection, then it checks if it can create a new connection (i.e. number of open connections < maximum allowed). If both are false then it has to wait until either a connection becomes idle or the number of open connections decreases. Connections should also be killed after they have been idle for a set amount of time.

Here is some (bad) pseudocode of what I have in mind. Could I have some suggestions?

func newTLSConnection(netDialer, host, tlsConfig) (tls.Con) {

    // Set up the certs
    // ...

    // Make A TLS Connection
    con, _ := tls.DialWithDialer(netDialer, "tcp", host, tlsConfig)

    return con
}

func (con tls.Con) Do (someData []byte) {

    // If con 
    // Send some date to the server
    _, _ := con.Write(someData)

    // Get response from server
    response := make([]byte, 100)
    _, _ := io.ReadFull(con, response)

    return
}


main(){
    var cons []tls.Con
    maxConSize := 3

    while {

        if allConsInSliceAreBusy() && len(cons) < maxConSize{
            newCon = NewTLSConnection(...)
            cons = append(cons, newCon)
            conToUse := newCon

            conToUse.Do([]byte("stuff"))

        } else if !allConsInSliceAreBusy() {

            conToUse := firstOpenConInCons()

            conToUse.Do([]byte("stuff"))

        } else{
             // NOP. Max cons created and they are all busy.
             // Wait for one to become idle or close.
        }
    }
}

Thank you!

  • 写回答

1条回答 默认 最新

  • dongweiben5229 2019-03-30 18:17
    关注

    What you ask about is called connection pooling. Have a look at Fasthttp package source code: https://github.com/valyala/fasthttp/blob/master/client.go You can even use this library or another one for your purpose.

    At line line 1252 you can find acquireConn func which does exactly what you need:

    • Locks connection pool to allow concurrent exection.
    • Creates new connections if pool is empty (new connections are pulled out of the pool).
    • Makes connections cleanup in case of TTL timout.
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog