Skip to content

Commit 4bd6246

Browse files
committed
fix: 复用 client,降低socket消耗
1 parent 4d77464 commit 4bd6246

File tree

4 files changed

+52
-46
lines changed

4 files changed

+52
-46
lines changed

botgo.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ func SelectOpenAPIVersion(version openapi.APIVersion) error {
3333
// NewOpenAPI 创建新的 openapi 实例,会返回当前的 openapi 实现的实例
3434
// 如果需要使用其他版本的实现,需要在调用这个方法之前调用 SelectOpenAPIVersion 方法
3535
func NewOpenAPI(token *token.Token) openapi.OpenAPI {
36-
return openapi.DefaultImpl.New(token, false)
36+
return openapi.DefaultImpl.Setup(token, false)
3737
}
3838

3939
// NewSandboxOpenAPI 创建测试环境的 openapi 实例
4040
func NewSandboxOpenAPI(token *token.Token) openapi.OpenAPI {
41-
return openapi.DefaultImpl.New(token, true)
41+
return openapi.DefaultImpl.Setup(token, true)
4242
}

examples/receive-and-send/process.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func (p Processor) ProcessMessage(input string, data *dto.WSATMessageData) error
3131
toCreate.Ark = genReplyArk(data)
3232
}
3333
if _, err := p.api.PostMessage(context.Background(), data.ChannelID, toCreate); err != nil {
34-
log.Fatalln(err)
34+
log.Println(err)
3535
}
3636
return nil
3737
}
@@ -60,7 +60,8 @@ func genReplyContent(data *dto.WSATMessageData) string {
6060
`
6161

6262
msgTime, _ := data.Timestamp.Time()
63-
return fmt.Sprintf(tpl,
63+
return fmt.Sprintf(
64+
tpl,
6465
message.MentionUser(data.Author.ID),
6566
message.MentionChannel(data.ChannelID),
6667
msgTime, time.Now().Format(time.RFC3339),

openapi/iface.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,9 @@ type OpenAPI interface {
2828
// Base 基础能力接口
2929
type Base interface {
3030
Version() APIVersion
31-
New(token *token.Token, inSandbox bool) OpenAPI
31+
Setup(token *token.Token, inSandbox bool) OpenAPI
3232
// WithTimeout 设置请求接口超时时间
3333
WithTimeout(duration time.Duration) OpenAPI
34-
// WithBody 设置 body,如果 openapi 提供设置 body 的功能,则需要自行识别 body 类型
35-
WithBody(body interface{}) OpenAPI
3634
// Transport 透传请求,如果 sdk 没有及时跟进新的接口的变更,可以使用该方法进行透传,openapi 实现时可以按需选择是否实现该接口
3735
Transport(ctx context.Context, method, url string, body interface{}) ([]byte, error)
3836
// TraceID 返回上一次请求的 trace id

openapi/v1/openapi.go

Lines changed: 46 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@ import (
1919
type openAPI struct {
2020
token *token.Token
2121
timeout time.Duration
22-
body interface{}
23-
sandbox bool
24-
debug bool
25-
trace string // trace id
22+
23+
sandbox bool // 请求沙箱环境
24+
debug bool // debug 模式,调试sdk时候使用
25+
lastTraceID string // lastTraceID id
26+
27+
restyClient *resty.Client // resty client 复用
2628
}
2729

2830
// Setup 注册
@@ -35,29 +37,25 @@ func (o *openAPI) Version() openapi.APIVersion {
3537
return openapi.APIv1
3638
}
3739

38-
// TraceID 获取 trace id
40+
// TraceID 获取 lastTraceID id
3941
func (o *openAPI) TraceID() string {
40-
return o.trace
42+
return o.lastTraceID
4143
}
4244

43-
// New 生成一个实例
44-
func (o *openAPI) New(token *token.Token, inSandbox bool) openapi.OpenAPI {
45-
return &openAPI{
45+
// Setup 生成一个实例
46+
func (o *openAPI) Setup(token *token.Token, inSandbox bool) openapi.OpenAPI {
47+
api := &openAPI{
4648
token: token,
4749
timeout: 3 * time.Second,
4850
sandbox: inSandbox,
4951
}
52+
api.setupClient() // 初始化可复用的 client
53+
return api
5054
}
5155

5256
// WithTimeout 设置请求接口超时时间
5357
func (o *openAPI) WithTimeout(duration time.Duration) openapi.OpenAPI {
54-
o.timeout = duration
55-
return o
56-
}
57-
58-
// WithBody 设置 body,如果 openapi 提供设置 body 的功能,则需要自行识别 body 类型
59-
func (o *openAPI) WithBody(body interface{}) openapi.OpenAPI {
60-
o.body = body
58+
o.restyClient.SetTimeout(duration)
6159
return o
6260
}
6361

@@ -67,42 +65,51 @@ func (o *openAPI) Transport(ctx context.Context, method, url string, body interf
6765
return resp.Body(), err
6866
}
6967

70-
func (o *openAPI) request(ctx context.Context) *resty.Request {
71-
client := resty.New().
68+
// 初始化 client
69+
func (o *openAPI) setupClient() {
70+
o.restyClient = resty.New().
7271
SetLogger(log.DefaultLogger).
7372
SetDebug(o.debug).
7473
SetTimeout(o.timeout).
7574
SetAuthToken(o.token.GetString()).
7675
SetAuthScheme(string(o.token.Type)).
7776
SetHeader("User-Agent", version.String()).
78-
SetPreRequestHook(func(client *resty.Client, request *http.Request) error {
79-
// 执行请求前过滤器
80-
// 由于在 `OnBeforeRequest` 的时候,request 还没生成,所以 filter 不能使用,所以放到 `PreRequestHook`
81-
return openapi.DoReqFilterChains(request, nil)
82-
}).
77+
SetPreRequestHook(
78+
func(client *resty.Client, request *http.Request) error {
79+
// 执行请求前过滤器
80+
// 由于在 `OnBeforeRequest` 的时候,request 还没生成,所以 filter 不能使用,所以放到 `PreRequestHook`
81+
return openapi.DoReqFilterChains(request, nil)
82+
},
83+
).
8384
// 设置请求之后的钩子,打印日志,判断状态码
84-
OnAfterResponse(func(client *resty.Client, resp *resty.Response) error {
85-
log.Infof("%v", respInfo(resp))
86-
// 执行请求后过滤器
87-
if err := openapi.DoRespFilterChains(resp.Request.RawRequest, resp.RawResponse); err != nil {
88-
return err
89-
}
90-
o.trace = resp.Header().Get(openapi.TraceIDKey)
91-
// 非成功含义的状态码,需要返回 error 供调用方识别
92-
if !openapi.IsSuccessStatus(resp.StatusCode()) {
93-
return errs.New(resp.StatusCode(), string(resp.Body()), o.trace)
94-
}
95-
return nil
96-
})
85+
OnAfterResponse(
86+
func(client *resty.Client, resp *resty.Response) error {
87+
log.Infof("%v", respInfo(resp))
88+
// 执行请求后过滤器
89+
if err := openapi.DoRespFilterChains(resp.Request.RawRequest, resp.RawResponse); err != nil {
90+
return err
91+
}
92+
traceID := resp.Header().Get(openapi.TraceIDKey)
93+
o.lastTraceID = traceID
94+
// 非成功含义的状态码,需要返回 error 供调用方识别
95+
if !openapi.IsSuccessStatus(resp.StatusCode()) {
96+
return errs.New(resp.StatusCode(), string(resp.Body()), traceID)
97+
}
98+
return nil
99+
},
100+
)
101+
}
97102

98-
return client.R().
99-
SetContext(ctx)
103+
// request 每个请求,都需要创建一个 request
104+
func (o *openAPI) request(ctx context.Context) *resty.Request {
105+
return o.restyClient.R().SetContext(ctx)
100106
}
101107

102108
// respInfo 用于输出日志的时候格式化数据
103109
func respInfo(resp *resty.Response) string {
104110
bodyJSON, _ := json.Marshal(resp.Request.Body)
105-
return fmt.Sprintf("[OPENAPI]%v %v, trace:%v, status:%v, elapsed:%v req: %v, resp: %v",
111+
return fmt.Sprintf(
112+
"[OPENAPI]%v %v, traceID:%v, status:%v, elapsed:%v req: %v, resp: %v",
106113
resp.Request.Method,
107114
resp.Request.URL,
108115
resp.Header().Get(openapi.TraceIDKey),

0 commit comments

Comments
 (0)