网络环境调整

This commit is contained in:
2026-04-20 19:46:33 +08:00
parent d757d25504
commit aeced7874c

View File

@@ -53,78 +53,6 @@ func connectConsul(ctx context.Context) error {
return nil return nil
} }
// startHealthCheckAndReconnect 启动健康检查和自动重连
func startHealthCheckAndReconnect() {
if reconnectDone != nil {
close(reconnectDone)
}
reconnectDone = make(chan struct{})
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
ctx := context.Background()
// 初始化HTTP客户端用于健康检查
httpClient = &http.Client{
Timeout: 30 * time.Second,
}
for {
select {
case <-ticker.C:
// 检查服务发现是否正常工作
if checkConsulHealth(ctx) {
continue
}
g.Log().Warning(ctx, "⚠️ Consul 连接异常,尝试重新连接...")
// 重置连接状态并重连
reconnectMutex.Lock()
connected = false
registry = nil
reconnectMutex.Unlock()
if err := connectConsul(ctx); err != nil {
g.Log().Errorf(ctx, "❌ Consul 重连失败: %v,30秒后重试...", err)
}
case <-reconnectDone:
g.Log().Info(ctx, "🛑 Consul 健康检查已停止")
return
}
}
}
// checkConsulHealth 检查 Consul 健康状态
func checkConsulHealth(ctx context.Context) bool {
reconnectMutex.RLock()
defer reconnectMutex.RUnlock()
if registry == nil || !connected {
return false
}
// 使用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
}
func init() { func init() {
ctx := context.Background() ctx := context.Background()
@@ -136,8 +64,6 @@ func init() {
if err := connectConsul(ctx); err != nil { if err := connectConsul(ctx); err != nil {
g.Log().Errorf(ctx, "❌ Consul 初始化失败: %v", err) g.Log().Errorf(ctx, "❌ Consul 初始化失败: %v", err)
} else {
go startHealthCheckAndReconnect()
} }
loadConfigFromConsul() loadConfigFromConsul()