|
- package participantservicelogic
-
- import (
- "fmt"
- "github.com/zeromicro/go-zero/core/logx"
- "sync"
- "time"
- )
-
- type Client struct {
- Host string
- Port string
- ParticipantID int64
- LastHeartbeat time.Time
- ClientState string
- }
-
- var (
- ParticipantClients = make(map[string]*Client)
- clientsMutex sync.Mutex
- healthCheckTime = 5 * time.Second
- unhealthyTime = 15 * time.Second
- removeTime = 30 * time.Second
- )
-
- func SendHeartbeat(host string, port string, participantID int64) {
- key := fmt.Sprintf("%s:%d-%d", host, port, participantID)
-
- clientsMutex.Lock()
- defer clientsMutex.Unlock()
-
- if client, ok := ParticipantClients[key]; ok {
- client.LastHeartbeat = time.Now()
- } else {
- ParticipantClients[key] = &Client{
- Host: host,
- Port: port,
- ParticipantID: participantID,
- LastHeartbeat: time.Now(),
- ClientState: "TRUE",
- }
- }
- }
-
- // CheckHealth 检测心跳健康
- func CheckHealth() {
- clientsMutex.Lock()
- defer clientsMutex.Unlock()
-
- for key, client := range ParticipantClients {
- if time.Since(client.LastHeartbeat) > unhealthyTime {
- client.ClientState = "UNKNOWN"
- if time.Since(client.LastHeartbeat) > removeTime {
- delete(ParticipantClients, key)
- logx.Infof("Unhealthy client removed: %s\n", key)
- }
- }
- }
- }
|