feat: gateway.Endpoint 支持设置重连间隔

This commit is contained in:
kercylan98 2023-08-24 16:45:32 +08:00
parent 30e7894a37
commit cdfecb41e8
2 changed files with 27 additions and 2 deletions

View File

@ -8,6 +8,8 @@ import (
"time"
)
var DefaultEndpointReconnectInterval = time.Second
// NewEndpoint 创建网关端点
func NewEndpoint(name string, cli *client.Client, options ...EndpointOption) *Endpoint {
endpoint := &Endpoint{
@ -15,6 +17,7 @@ func NewEndpoint(name string, cli *client.Client, options ...EndpointOption) *En
name: name,
address: cli.GetServerAddr(),
connections: haxmap.New[string, *server.Conn](),
rci: DefaultEndpointReconnectInterval,
}
for _, option := range options {
option(endpoint)
@ -36,6 +39,7 @@ type Endpoint struct {
state float64 // 端点健康值0为不可用越高越优
evaluator func(costUnixNano float64) float64 // 端点健康值评估函数
connections *haxmap.Map[string, *server.Conn] // 被该端点转发的连接列表
rci time.Duration // 端点重连间隔
}
// connect 连接端点
@ -52,7 +56,12 @@ func (slf *Endpoint) connect(gateway *Gateway) {
slf.state = slf.evaluator(float64(time.Now().UnixNano() - cur))
break
}
time.Sleep(1000 * time.Millisecond)
if slf.rci > 0 {
time.Sleep(slf.rci)
} else {
slf.state = 0
break
}
}
})
slf.client.RegConnectionReceivePacketEvent(func(conn *client.Client, wst int, packet []byte) {
@ -76,7 +85,12 @@ func (slf *Endpoint) connect(gateway *Gateway) {
slf.state = slf.evaluator(float64(time.Now().UnixNano() - cur))
break
}
time.Sleep(1000 * time.Millisecond)
if slf.rci > 0 {
time.Sleep(slf.rci)
} else {
slf.state = 0
break
}
}
}

View File

@ -1,5 +1,7 @@
package gateway
import "time"
// EndpointOption 网关端点选项
type EndpointOption func(endpoint *Endpoint)
@ -9,3 +11,12 @@ func WithEndpointStateEvaluator(evaluator func(costUnixNano float64) float64) En
endpoint.evaluator = evaluator
}
}
// WithReconnectInterval 设置端点重连间隔
// - 默认为 DefaultEndpointReconnectInterval
// - 端点在连接失败后会在该间隔后重连,如果 <= 0 则不会重连
func WithReconnectInterval(interval time.Duration) EndpointOption {
return func(endpoint *Endpoint) {
endpoint.rci = interval
}
}