118 lines
2.7 KiB
Go
118 lines
2.7 KiB
Go
package reconnect
|
|
|
|
import "time"
|
|
|
|
// StrategyType 定义重连策略类型
|
|
type StrategyType string
|
|
|
|
const (
|
|
// StrategyExponentialBackoff 指数退避策略
|
|
StrategyExponentialBackoff StrategyType = "exponential"
|
|
// StrategyFixedInterval 固定间隔策略
|
|
StrategyFixedInterval StrategyType = "fixed"
|
|
// StrategyLinearBackoff 线性退避策略
|
|
StrategyLinearBackoff StrategyType = "linear"
|
|
)
|
|
|
|
// ConnectionState 连接状态
|
|
type ConnectionState int
|
|
|
|
const (
|
|
// StateDisconnected 断开连接
|
|
StateDisconnected ConnectionState = iota
|
|
// StateConnecting 正在连接
|
|
StateConnecting
|
|
// StateConnected 已连接
|
|
StateConnected
|
|
// StateReconnecting 正在重连
|
|
StateReconnecting
|
|
)
|
|
|
|
func (s ConnectionState) String() string {
|
|
switch s {
|
|
case StateDisconnected:
|
|
return "disconnected"
|
|
case StateConnecting:
|
|
return "connecting"
|
|
case StateConnected:
|
|
return "connected"
|
|
case StateReconnecting:
|
|
return "reconnecting"
|
|
default:
|
|
return "unknown"
|
|
}
|
|
}
|
|
|
|
// Config 重连配置
|
|
type Config struct {
|
|
// Strategy 重连策略类型
|
|
Strategy StrategyType
|
|
|
|
// MaxRetries 最大重试次数,-1 表示无限重试
|
|
MaxRetries int
|
|
|
|
// InitialDelay 初始延迟时间
|
|
InitialDelay time.Duration
|
|
|
|
// MaxDelay 最大延迟时间
|
|
MaxDelay time.Duration
|
|
|
|
// Multiplier 指数退避乘数(仅用于指数退避策略)
|
|
Multiplier float64
|
|
|
|
// LinearIncrement 线性增量(仅用于线性退避策略)
|
|
LinearIncrement time.Duration
|
|
|
|
// HealthCheckInterval 健康检查间隔
|
|
HealthCheckInterval time.Duration
|
|
|
|
// HealthCheckTimeout 健康检查超时时间
|
|
HealthCheckTimeout time.Duration
|
|
|
|
// OnStateChange 状态变化回调函数
|
|
OnStateChange func(oldState, newState ConnectionState)
|
|
|
|
// OnReconnect 重连回调函数(重连成功时调用)
|
|
OnReconnect func(attempt int)
|
|
|
|
// OnError 错误回调函数
|
|
OnError func(err error)
|
|
}
|
|
|
|
// DefaultConfig 返回默认配置
|
|
func DefaultConfig() Config {
|
|
return Config{
|
|
Strategy: StrategyExponentialBackoff,
|
|
MaxRetries: -1, // 无限重试
|
|
InitialDelay: 1 * time.Second,
|
|
MaxDelay: 30 * time.Second,
|
|
Multiplier: 2.0,
|
|
LinearIncrement: 1 * time.Second,
|
|
HealthCheckInterval: 10 * time.Second,
|
|
HealthCheckTimeout: 5 * time.Second,
|
|
}
|
|
}
|
|
|
|
// Validate 验证配置
|
|
func (c *Config) Validate() {
|
|
if c.InitialDelay <= 0 {
|
|
c.InitialDelay = 1 * time.Second
|
|
}
|
|
if c.MaxDelay <= 0 {
|
|
c.MaxDelay = 30 * time.Second
|
|
}
|
|
if c.Multiplier <= 0 {
|
|
c.Multiplier = 2.0
|
|
}
|
|
if c.LinearIncrement <= 0 {
|
|
c.LinearIncrement = 1 * time.Second
|
|
}
|
|
if c.HealthCheckInterval <= 0 {
|
|
c.HealthCheckInterval = 10 * time.Second
|
|
}
|
|
if c.HealthCheckTimeout <= 0 {
|
|
c.HealthCheckTimeout = 5 * time.Second
|
|
}
|
|
}
|
|
|