zhangzengfei
2024-10-22 a254bc563003a9e7b3a8f1307df38b8ae4274a4f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package client
 
import (
    "context"
    "fmt"
    "math/rand"
    "time"
 
    "gat1400Exchange/config"
    "gat1400Exchange/pkg/logger"
    "gat1400Exchange/vo"
)
 
func Init1400Client(ctx context.Context) {
    if !config.ClientConf.Enable {
        logger.Debug("GAT/1400 Client disabled")
        return
    }
 
    go registerLoop(ctx)
    go keepaliveLoop(ctx)
    go syncTimeLoop(ctx)
}
 
func registerLoop(ctx context.Context) {
    ticker := time.NewTicker(1 * time.Second)
    for {
        select {
        case <-ctx.Done():
            unRegister()
            return
        case <-ticker.C:
            if clientStatus != vo.StatusSuccess {
                fmt.Println("register")
                if !register() {
                    randNum := rand.Intn(300) + 1
                    // 随机等待300s, 重新注册
                    ticker.Reset(time.Duration(randNum) * time.Second)
                } else {
                    ticker.Reset(1 * time.Second)
                }
            }
        }
    }
}
 
func keepaliveLoop(ctx context.Context) {
    var failCount int
    ticker := time.NewTicker(time.Duration(config.ClientConf.HeartbeatInterval) * time.Second)
    for {
        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            if status := keepalive(); status != vo.StatusSuccess {
                failCount++
 
                if failCount > config.ClientConf.HeartbeatFailCount {
                    clientStatus = status
                }
            } else {
                failCount = 0
            }
        }
    }
}
 
func syncTimeLoop(ctx context.Context) {
    ticker := time.NewTicker(time.Duration(config.ClientConf.HeartbeatInterval*10) * time.Second)
    for {
        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            syncTime()
        }
    }
}