Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用Hertz 客户端相关功能。提示connection is closed by peer while being in the connection pool #1239

Closed
MakePeng opened this issue Nov 28, 2024 · 2 comments
Labels
invalid issue invalid issue (not related to Hertz or described in document or not enough information provided) stale

Comments

@MakePeng
Copy link

package utils

import (
"context"
"encoding/json"
"github.com/cloudwego/hertz/pkg/app/client"
"github.com/cloudwego/hertz/pkg/app/client/retry"
"github.com/cloudwego/hertz/pkg/common/config"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/protocol"
"net/http"
"net/url"
"sync"
"time"
)

var (
httpClient *client.Client
once sync.Once
)

// newClient
//
// @description: hertz客户端初始化
// @return client.Client
// @return error
func newClient() (client.Client, error) {
c, err := client.NewClient(
client.WithDialTimeout(3
time.Second),
client.WithMaxConnsPerHost(1024), //每个主机可能建立的最大连接数
client.WithMaxConnDuration(10
time.Second), //最大的连接持续时间,keep-alive 连接在此持续时间后被关闭
client.WithMaxConnWaitTimeout(10time.Second), //等待空闲连接的最大时间
client.WithClientReadTimeout(10
time.Second), //完整读取响应(包括 body)的最大持续时间
client.WithWriteTimeout(10time.Second), //HTTP 客户端的写入超时时间
client.WithRetryConfig(
retry.WithMaxAttemptTimes(3), // 最大的尝试次数,包括初始调用
retry.WithInitDelay(60
time.Millisecond), // 初始延迟
retry.WithMaxDelay(60time.Millisecond), // 最大延迟,不管重试多少次,策略如何,都不会超过这个延迟
retry.WithMaxJitter(60
time.Millisecond), // 延时的最大扰动,结合 RandomDelayPolicy 才会有效果
retry.WithDelayPolicy(retry.CombineDelay(retry.FixedDelayPolicy, retry.BackOffDelayPolicy, retry.RandomDelayPolicy)),
),
)

return c, err

}

// getGloBalClient
//
// @description: 获取全局的单例客户端
// @return *client.Client
func getGloBalClient() *client.Client {
once.Do(func() {
httpClient, _ = newClient()
})
return httpClient
}

// Do
//
// @description: 执行http请请求方法
// @param method
// @param urlStr
// @param body
// @param headers
// @param params
// @param respType
// @return error
func Do(method, urlStr string, body interface{}, headers map[string]string, params url.Values, respType interface{}) error {
//c, err := newClient()
//if err != nil {
// return err
//}
c := getGloBalClient()
req := &protocol.Request{}
res := &protocol.Response{}
//请求设置
req.SetOptions(config.WithDialTimeout(1time.Second),
config.WithReadTimeout(3
time.Second),
config.WithWriteTimeout(3*time.Second))
//设置请求方式
req.SetMethod(method)
//设置请求url
req.SetRequestURI(urlStr)
//设置请求头
for k, v := range headers {
req.SetHeader(k, v)
}
// 设置查询参数
if params != nil {
req.SetQueryString(params.Encode())
}
//设置body
if body != nil {
req.Header.SetContentTypeBytes([]byte("application/json"))
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
req.SetBody(bodyBytes)
}
err := c.Do(context.Background(), req, res)
if err != nil {
return err
}

// 解析响应数据到respType
if respType != nil {
	err = json.Unmarshal(res.Body(), respType)
	if err != nil {
		hlog.Errorf("convert res is fail err:%v bodys :%v status :%v", err, string(res.Body()), res.StatusCode())
		return err
	}
}
return nil

}

// SendGet
//
// @description: 发起GET请求
// @receiver c
// @param url
// @param headers
// @param params
// @param respType
// @return error
func SendGet(url string, headers map[string]string, params url.Values, respType interface{}) error {
return Do(http.MethodGet, url, nil, headers, params, respType)
}

// SendPost
//
// @description: 发起POST请求
// @receiver c
// @param url
// @param body
// @param headers
// @param params
// @param respType
// @return error
func SendPost(url string, body interface{}, headers map[string]string, params url.Values, respType interface{}) error {
return Do(http.MethodPost, url, body, headers, params, respType)
}
客户端请求类代码如下,帮忙看下啥问题

@github-actions github-actions bot added the invalid issue invalid issue (not related to Hertz or described in document or not enough information provided) label Nov 28, 2024
Copy link

This issue has been marked as invalid question, please give more information by following the issue template. The issue will be closed in 1 days if no further activity occurs.

@GuangmingLuo
Copy link
Member

@MakePeng 按照 issue 模板提交 issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
invalid issue invalid issue (not related to Hertz or described in document or not enough information provided) stale
Development

No branches or pull requests

2 participants