自动重连套路
思路
-
结构体:
静态配置
动态链接
链接关闭字段
数据管道
-
initConfig()
-
run()
重试机制
-
Watch()
代码
package main
import (
"log"
"net"
"strconv"
"time"
)
const (
MaxSend = 1000
)
type Producer struct {
ConfAddr string
Conn net.Conn // 像这种链接的动态属性就要去监控
isHealthy bool
Msg chan string
}
func NewProducer(addr string) *Producer {
return &Producer{
ConfAddr: addr,
isHealthy: false,
Msg: make(chan string, MaxSend),
}
}
func (p *Producer)initConfig() error {
log.Println("初始化配置")
dial, err := net.Dial("tcp", p.ConfAddr)
if err != nil {
p.isHealthy = false
log.Println(err)
return err
}
p.Conn = dial
p.isHealthy = true
return nil
}
func (p *Producer) run() {
retry := 0
for p.isHealthy {
data := <- p.Msg
log.Println("收到数据", data)
p.Conn, _ = net.Dial("tcp", p.ConfAddr)
_, err := p.Conn.Write([]byte(data))
if err != nil {
log.Println(err)
retry++
if retry > 10 {
p.isHealthy = false
return
}
continue
}
retry = 0
}
}
func (p *Producer)Watch() {
for {
if p.isHealthy {
time.Sleep(time.Second)
continue
}
err := p.initConfig()
if err != nil {
log.Println("配置初始化失败")
continue
}
p.run()
}
}
func main() {
producer := NewProducer("127.0.0.1:9666")
go func() {
ticker := time.NewTicker(time.Second)
for {
<-ticker.C
producer.Msg <- strconv.Itoa(time.Now().Second())
}
}()
producer.Watch()
}