如何在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!

duanluwei9374
duanluwei9374 “执行”功能通过TLS连接发送数据并读取响应。
一年多之前 回复
douyou2368
douyou2368 该代码段不可读...您试图用此行func(contls.Con)做什么(someData[]byte)?
一年多之前 回复

1个回答



您询问的问题称为连接池。 看看Fasthttp包的源代码: https://github.com/valyala /fasthttp/blob/master/client.go 您甚至可以根据需要使用此库或其他库。</ p>

在第 1252 您可以找到 acquireConn </ code>函数,它完全满足您的需求:< / p>


  • 锁定连接池以允许并发执行。</ li>
  • 如果池为空(从池中拉出新连接),则创建新连接。 </ li>
  • 在TTL超时的情况下进行连接清除。</ li>
    </ ul>
    </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐