Skip to content

Commit 177fc63

Browse files
authored
Merge pull request #84 from AlexStocks/refactor/tcp_reconnect_var_rename
Improvement: rename the variables in TCP reconnect function and some default constants
2 parents da9fedf + bace946 commit 177fc63

File tree

6 files changed

+66
-45
lines changed

6 files changed

+66
-45
lines changed

examples/echo/tcp-echo/client/app/config.go

+17-16
Original file line numberDiff line numberDiff line change
@@ -42,22 +42,23 @@ var conf *Config
4242

4343
type (
4444
GettySessionParam struct {
45-
CompressEncoding bool `default:"false" yaml:"compress_encoding" json:"compress_encoding,omitempty"`
46-
TcpNoDelay bool `default:"true" yaml:"tcp_no_delay" json:"tcp_no_delay,omitempty"`
47-
TcpKeepAlive bool `default:"true" yaml:"tcp_keep_alive" json:"tcp_keep_alive,omitempty"`
48-
KeepAlivePeriod string `default:"180s" yaml:"keep_alive_period" json:"keep_alive_period,omitempty"`
49-
keepAlivePeriod time.Duration
50-
TcpRBufSize int `default:"262144" yaml:"tcp_r_buf_size" json:"tcp_r_buf_size,omitempty"`
51-
TcpWBufSize int `default:"65536" yaml:"tcp_w_buf_size" json:"tcp_w_buf_size,omitempty"`
52-
PkgWQSize int `default:"1024" yaml:"pkg_wq_size" json:"pkg_wq_size,omitempty"`
53-
TcpReadTimeout string `default:"1s" yaml:"tcp_read_timeout" json:"tcp_read_timeout,omitempty"`
54-
tcpReadTimeout time.Duration
55-
TcpWriteTimeout string `default:"5s" yaml:"tcp_write_timeout" json:"tcp_write_timeout,omitempty"`
56-
tcpWriteTimeout time.Duration
57-
WaitTimeout string `default:"7s" yaml:"wait_timeout" json:"wait_timeout,omitempty"`
58-
waitTimeout time.Duration
59-
MaxMsgLen int `default:"1024" yaml:"max_msg_len" json:"max_msg_len,omitempty"`
60-
SessionName string `default:"echo-client" yaml:"session_name" json:"session_name,omitempty"`
45+
CompressEncoding bool `default:"false" yaml:"compress_encoding" json:"compress_encoding,omitempty"`
46+
TcpNoDelay bool `default:"true" yaml:"tcp_no_delay" json:"tcp_no_delay,omitempty"`
47+
TcpKeepAlive bool `default:"true" yaml:"tcp_keep_alive" json:"tcp_keep_alive,omitempty"`
48+
KeepAlivePeriod string `default:"180s" yaml:"keep_alive_period" json:"keep_alive_period,omitempty"`
49+
keepAlivePeriod time.Duration
50+
TcpRBufSize int `default:"262144" yaml:"tcp_r_buf_size" json:"tcp_r_buf_size,omitempty"`
51+
TcpWBufSize int `default:"65536" yaml:"tcp_w_buf_size" json:"tcp_w_buf_size,omitempty"`
52+
PkgWQSize int `default:"1024" yaml:"pkg_wq_size" json:"pkg_wq_size,omitempty"`
53+
TcpReadTimeout string `default:"1s" yaml:"tcp_read_timeout" json:"tcp_read_timeout,omitempty"`
54+
tcpReadTimeout time.Duration
55+
TcpWriteTimeout string `default:"5s" yaml:"tcp_write_timeout" json:"tcp_write_timeout,omitempty"`
56+
tcpWriteTimeout time.Duration
57+
WaitTimeout string `default:"7s" yaml:"wait_timeout" json:"wait_timeout,omitempty"`
58+
waitTimeout time.Duration
59+
MaxMsgLen int `default:"1024" yaml:"max_msg_len" json:"max_msg_len,omitempty"`
60+
SessionName string `default:"echo-client" yaml:"session_name" json:"session_name,omitempty"`
61+
TcpMaxReconnectAttempts int `default:"10" yaml:"tcp_max_reconnect_attempts" json:"tcp_max_reconnect_attempts,omitempty"`
6162
}
6263

6364
// Config holds supported types by the multiconfig package

examples/echo/tcp-echo/client/app/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ func newSession(session getty.Session) error {
124124
func initClient() {
125125
clientOpts := []getty.ClientOption{getty.WithServerAddress(gxnet.HostAddress(conf.ServerHost, conf.ServerPort))}
126126
clientOpts = append(clientOpts, getty.WithClientTaskPool(taskPool))
127-
127+
clientOpts = append(clientOpts, getty.WithReconnectAttempts(conf.GettySessionParam.TcpMaxReconnectAttempts))
128128
if conf.ConnectionNum != 0 {
129129
clientOpts = append(clientOpts, getty.WithConnectionNumber(conf.ConnectionNum))
130130
}

transport/client.go

+28-22
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"crypto/x509"
2323
"encoding/pem"
2424
"fmt"
25+
"math"
2526
"net"
2627
"os"
2728
"strings"
@@ -41,10 +42,11 @@ import (
4142
)
4243

4344
const (
44-
reconnectInterval = 3e8 // 300ms
45-
connectInterval = 5e8 // 500ms
46-
connectTimeout = 3e9
47-
maxTimes = 10
45+
defaultReconnectInterval = 3e8 // 300ms
46+
connectInterval = 5e8 // 500ms
47+
connectTimeout = 3e9
48+
defaultMaxReconnectAttempts = 50
49+
maxBackOffTimes = 10
4850
)
4951

5052
var (
@@ -207,14 +209,18 @@ func (c *client) dialUDP() Session {
207209
}
208210

209211
// check connection alive by write/read action
210-
conn.SetWriteDeadline(time.Now().Add(1e9))
212+
if err := conn.SetWriteDeadline(time.Now().Add(1e9)); err != nil {
213+
log.Warnf("failed to set write deadline: %+v", err)
214+
}
211215
if length, err = conn.Write(connectPingPackage[:]); err != nil {
212216
conn.Close()
213217
log.Warnf("conn.Write(%s) = {length:%d, err:%+v}", string(connectPingPackage), length, perrors.WithStack(err))
214218
<-gxtime.After(connectInterval)
215219
continue
216220
}
217-
conn.SetReadDeadline(time.Now().Add(1e9))
221+
if err := conn.SetReadDeadline(time.Now().Add(1e9)); err != nil {
222+
log.Warnf("failed to set read deadline: %+v", err)
223+
}
218224
length, err = conn.Read(buf)
219225
if netErr, ok := perrors.Cause(err).(net.Error); ok && netErr.Timeout() {
220226
err = nil
@@ -423,33 +429,33 @@ func (c *client) RunEventLoop(newSession NewSessionCallback) {
423429
// a for-loop connect to make sure the connection pool is valid
424430
func (c *client) reConnect() {
425431
var (
426-
num, max, times, interval int
427-
maxDuration int64
432+
sessionNum, reconnectAttempts int
433+
maxReconnectInterval int64
428434
)
429-
max = c.number
430-
interval = c.reconnectInterval
431-
if interval == 0 {
432-
interval = reconnectInterval
435+
reconnectInterval := c.reconnectInterval
436+
if reconnectInterval == 0 {
437+
reconnectInterval = defaultReconnectInterval
438+
}
439+
maxReconnectAttempts := c.maxReconnectAttempts
440+
if maxReconnectAttempts == 0 {
441+
maxReconnectAttempts = defaultMaxReconnectAttempts
433442
}
443+
connPoolSize := c.number
434444
for {
435445
if c.IsClosed() {
436446
log.Warnf("client{peer:%s} goroutine exit now.", c.addr)
437447
break
438448
}
439449

440-
num = c.sessionNum()
441-
if max <= num || max < times {
442-
//Exit when the number of connection pools is sufficient or the reconnection times exceeds the connections numbers.
450+
sessionNum = c.sessionNum()
451+
if connPoolSize <= sessionNum || maxReconnectAttempts < reconnectAttempts {
452+
//exit reconnect when the number of connection pools is sufficient or the current reconnection attempts exceeds the max reconnection attempts.
443453
break
444454
}
445455
c.connect()
446-
times++
447-
if times > maxTimes {
448-
maxDuration = int64(maxTimes) * int64(interval)
449-
} else {
450-
maxDuration = int64(times) * int64(interval)
451-
}
452-
<-gxtime.After(time.Duration(maxDuration))
456+
reconnectAttempts++
457+
maxReconnectInterval = int64(math.Min(float64(reconnectAttempts), float64(maxBackOffTimes))) * int64(reconnectInterval)
458+
<-gxtime.After(time.Duration(maxReconnectInterval))
453459
}
454460
}
455461

transport/client_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ func TestTCPClient(t *testing.T) {
115115
WithServerAddress(addr.String()),
116116
WithReconnectInterval(5e8),
117117
WithConnectionNumber(1),
118+
WithReconnectAttempts(10),
118119
)
119120
assert.NotNil(t, clt)
120121
assert.True(t, clt.ID() > 0)

transport/options.go

+13-4
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,10 @@ func WithServerTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ServerOption
100100
type ClientOption func(*ClientOptions)
101101

102102
type ClientOptions struct {
103-
addr string
104-
number int
105-
reconnectInterval int // reConnect Interval
106-
103+
addr string
104+
number int
105+
reconnectInterval int // reConnect Interval
106+
maxReconnectAttempts int // max reconnect attempts
107107
// tls
108108
sslEnabled bool
109109
tlsConfigBuilder TlsConfigBuilder
@@ -168,3 +168,12 @@ func WithClientTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ClientOption
168168
o.tlsConfigBuilder = tlsConfigBuilder
169169
}
170170
}
171+
172+
// WithReconnectAttempts @maxReconnectAttempts is max reconnect attempts.
173+
func WithReconnectAttempts(maxReconnectAttempts int) ClientOption {
174+
return func(o *ClientOptions) {
175+
if 0 < maxReconnectAttempts {
176+
o.maxReconnectAttempts = maxReconnectAttempts
177+
}
178+
}
179+
}

transport/session.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,12 @@ func (s *session) stop() {
860860
// let read/Write timeout asap
861861
now := time.Now()
862862
if conn := s.Conn(); conn != nil {
863-
conn.SetReadDeadline(now.Add(s.ReadTimeout()))
864-
conn.SetWriteDeadline(now.Add(s.WriteTimeout()))
863+
if err := conn.SetReadDeadline(now.Add(s.ReadTimeout())); err != nil {
864+
log.Warnf("failed to set read deadline: %+v", err)
865+
}
866+
if err := conn.SetWriteDeadline(now.Add(s.WriteTimeout())); err != nil {
867+
log.Warnf("failed to set write deadline: %+v", err)
868+
}
865869
}
866870
close(s.done)
867871
clt, cltFound := s.GetAttribute(sessionClientKey).(*client)

0 commit comments

Comments
 (0)