Dockerfile

This commit is contained in:
2026-04-01 14:19:50 +08:00
parent 0ad6bc9438
commit 41b2a37fc0

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net"
"net/http"
"sync"
"time"
@@ -21,6 +22,7 @@ var (
reconnectMutex sync.RWMutex
reconnectDone chan struct{}
connected bool
httpClient *http.Client
)
// connectConsul 连接 Consul
@@ -45,9 +47,6 @@ func connectConsul(ctx context.Context) error {
connected = true
g.Log().Infof(ctx, "✅ Consul 初始化成功: %s", consulAddr)
// 启动健康检查和自动重连(只启动一次)
go startHealthCheckAndReconnect()
return nil
}
@@ -58,11 +57,16 @@ func startHealthCheckAndReconnect() {
}
reconnectDone = make(chan struct{})
ticker := time.NewTicker(5 * time.Second)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
ctx := context.Background()
// 初始化HTTP客户端用于健康检查
httpClient = &http.Client{
Timeout: 5 * time.Second,
}
for {
select {
case <-ticker.C:
@@ -80,7 +84,7 @@ func startHealthCheckAndReconnect() {
reconnectMutex.Unlock()
if err := connectConsul(ctx); err != nil {
g.Log().Errorf(ctx, "❌ Consul 重连失败: %v,5秒后重试...", err)
g.Log().Errorf(ctx, "❌ Consul 重连失败: %v,30秒后重试...", err)
}
case <-reconnectDone:
@@ -99,7 +103,22 @@ func checkConsulHealth(ctx context.Context) bool {
return false
}
// 简单检查注册器是否可用避免频繁调用Search导致错误
// 使用consul原生API进行健康检查
// 调用 /v1/agent/self 接口检测连接状态
url := fmt.Sprintf("http://%s/v1/agent/self", consulAddr)
resp, err := httpClient.Get(url)
if err != nil {
g.Log().Debugf(ctx, "Consul 健康检查失败: %v", err)
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
g.Log().Debugf(ctx, "Consul 健康检查失败,状态码: %d", resp.StatusCode)
return false
}
g.Log().Debugf(ctx, "✅ Consul 健康检查通过")
return true
}
@@ -109,8 +128,12 @@ func init() {
g.Log().Warning(context.Background(), "⚠️ Consul 配置未找到,跳过初始化")
return
}
if err := connectConsul(context.Background()); err != nil {
g.Log().Errorf(context.Background(), "❌ Consul 初始化失败: %v", err)
} else {
// 连接成功后启动健康检查和自动重连
go startHealthCheckAndReconnect()
}
}
func getLocalIP() (string, error) {