Skip to content

Commit

Permalink
feat: gateway.Endpoint 支持设置重连间隔
Browse files Browse the repository at this point in the history
  • Loading branch information
kercylan98 committed Aug 24, 2023
1 parent 30e7894 commit cdfecb4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
18 changes: 16 additions & 2 deletions server/gateway/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import (
"time"
)

var DefaultEndpointReconnectInterval = time.Second

// NewEndpoint 创建网关端点
func NewEndpoint(name string, cli *client.Client, options ...EndpointOption) *Endpoint {
endpoint := &Endpoint{
client: cli,
name: name,
address: cli.GetServerAddr(),
connections: haxmap.New[string, *server.Conn](),
rci: DefaultEndpointReconnectInterval,
}
for _, option := range options {
option(endpoint)
Expand All @@ -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 连接端点
Expand All @@ -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) {
Expand All @@ -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
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions server/gateway/endpoint_options.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package gateway

import "time"

// EndpointOption 网关端点选项
type EndpointOption func(endpoint *Endpoint)

Expand All @@ -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
}
}

0 comments on commit cdfecb4

Please sign in to comment.