90 lines
1.7 KiB
Go
90 lines
1.7 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"bash_go_service/shared/pkg/constants"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type Client struct {
|
|
baseURL string
|
|
client *http.Client
|
|
cancel context.CancelFunc // 添加一个取消函数
|
|
ctx context.Context
|
|
wg sync.WaitGroup // 添加WaitGroup来追踪请求
|
|
}
|
|
|
|
func (c *Client) Destroy() {
|
|
if c.cancel != nil {
|
|
c.cancel() // 取消所有使用此context的请求
|
|
}
|
|
c.client.CloseIdleConnections()
|
|
}
|
|
|
|
func (c *Client) Wait() {
|
|
c.wg.Wait()
|
|
}
|
|
|
|
// 在发起请求时增加计数
|
|
func (c *Client) trackRequest() {
|
|
c.wg.Add(1)
|
|
}
|
|
|
|
// 请求完成时减少计数
|
|
func (c *Client) requestDone() {
|
|
c.wg.Done()
|
|
}
|
|
|
|
type ClientOption func(*Client)
|
|
|
|
func WithBaseURL(baseURL string) ClientOption {
|
|
return func(c *Client) {
|
|
if baseURL != "" {
|
|
c.baseURL = baseURL
|
|
}
|
|
}
|
|
}
|
|
|
|
func init() {
|
|
viper.SetDefault("machine_registry.endpoint", "https://smart-bm.zjuici.com/oak-api/endpoint")
|
|
}
|
|
|
|
func NewClient(opts ...ClientOption) *Client {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
client := &Client{
|
|
baseURL: viper.GetString("machine_registry.endpoint"),
|
|
ctx: ctx,
|
|
cancel: cancel,
|
|
client: &http.Client{
|
|
Transport: &http.Transport{
|
|
DialContext: (&net.Dialer{
|
|
Timeout: constants.ConnectionTimeout,
|
|
KeepAlive: constants.KeepaliveTimeout,
|
|
}).DialContext,
|
|
ResponseHeaderTimeout: 30 * time.Second,
|
|
IdleConnTimeout: constants.IdleConnTimeout,
|
|
TLSHandshakeTimeout: 30 * time.Second,
|
|
MaxIdleConns: 100,
|
|
MaxIdleConnsPerHost: 100,
|
|
},
|
|
Timeout: constants.ClientTimeout,
|
|
},
|
|
}
|
|
|
|
for _, opt := range opts {
|
|
opt(client)
|
|
}
|
|
|
|
return client
|
|
}
|
|
|
|
// 长连接流式处理
|
|
type MessageHandler func(message string)
|