1 Star 0 Fork 0

Uni-Minds/utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
http_client_pool.go 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
Liuxy 提交于 2022-10-15 14:14 . Release 1.0.0
package tools
import (
"crypto/tls"
"fmt"
"net/http"
"time"
)
const timeout = 10 * time.Second
type ClientPool struct {
clients chan *http.Client
clientUsed int
clientMax int
}
func NewClientPool(maxClients int) *ClientPool {
pool := new(ClientPool)
pool.Init(maxClients)
return pool
}
func (p *ClientPool) Init(maxClients int) {
p.clientMax = maxClients
p.clients = make(chan *http.Client, maxClients)
}
func (p *ClientPool) GetClient() (client *http.Client) {
t := time.NewTicker(timeout)
for {
select {
case client = <-p.clients:
p.clientUsed += 1
return client
case <-t.C:
fmt.Println("number of clients reach max, no more available")
return nil
default:
if p.clientUsed < p.clientMax {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSHandshakeTimeout: timeout,
ResponseHeaderTimeout: timeout,
ExpectContinueTimeout: timeout,
}
client = &http.Client{
Transport: tr,
Timeout: timeout,
}
p.clientUsed += 1
fmt.Printf("generate new client, %d use / %d max\n", p.clientUsed, p.clientMax)
return client
}
}
}
}
func (p *ClientPool) Recycle(client *http.Client) {
if client != nil {
p.clientUsed -= 1
p.clients <- client
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/uni-minds/utils.git
git@gitee.com:uni-minds/utils.git
uni-minds
utils
utils
v1.0.1

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385