feat(api): 优化HTTP连接池和并发控制
- 增加IdleConnTimeout从30秒到30分钟 - 添加并发请求限制通道,最大同时请求数为10 - 实现InitConn函数用于预创建连接池 - 在UploadDataToServer中添加请求限流控制 - 优化资源清理逻辑,使用defer确保响应体关闭 - 重命名runtime包别名以避免冲突 - 在uploader中添加连接池初始化日志 - 添加panic恢复机制和错误处理
This commit is contained in:
+33
-3
@@ -3,6 +3,7 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"dypid-client/internal/config"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -13,12 +14,39 @@ var httpClient = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: 500,
|
||||
MaxIdleConnsPerHost: 500,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
IdleConnTimeout: 30 * time.Minute,
|
||||
},
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
var limit chan struct{}
|
||||
|
||||
func init() {
|
||||
//限制同时请求数为500
|
||||
limit = make(chan struct{}, 10)
|
||||
}
|
||||
|
||||
// InitConn 创建连接池
|
||||
func InitConn() {
|
||||
for i := 0; i < 200; i++ {
|
||||
resp, err := httpClient.Get(config.APPConfig.Url + "/api/test")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func UploadDataToServer(ctx context.Context, data string) error {
|
||||
limit <- struct{}{}
|
||||
defer func() {
|
||||
<-limit
|
||||
}()
|
||||
|
||||
params := url.Values{}
|
||||
params.Set("token", config.APPConfig.Token)
|
||||
params.Set("data", data)
|
||||
@@ -38,8 +66,10 @@ func UploadDataToServer(ctx context.Context, data string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
defer func() {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
}()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user