goroutine

This commit is contained in:
Cold
2025-12-03 15:33:32 +08:00
committed by 张斌
parent 90780f6362
commit 0738f6f957
3 changed files with 114 additions and 34 deletions

View File

@@ -11,10 +11,12 @@ import (
)
var (
conn *amqp.Connection
channel *amqp.Channel
once sync.Once
mu sync.RWMutex
conn *amqp.Connection
channel *amqp.Channel
once sync.Once
mu sync.RWMutex
closeWatcher chan struct{} // 用于停止监听 goroutine
watcherStarted bool // 防止重复启动监听
)
// Config RabbitMQ 配置
@@ -53,8 +55,14 @@ func Init(ctx context.Context, cfg *Config) error {
return
}
// 监听连接关闭
go handleConnectionClose(ctx)
// 初始化关闭监听器
closeWatcher = make(chan struct{})
// 监听连接关闭(只启动一次)
if !watcherStarted {
go handleConnectionClose(ctx)
watcherStarted = true
}
g.Log().Info(ctx, "RabbitMQ 连接成功")
})
@@ -101,13 +109,38 @@ func GetConnection() (*amqp.Connection, error) {
// handleConnectionClose 监听连接关闭并重连
func handleConnectionClose(ctx context.Context) {
closeErr := make(chan *amqp.Error)
conn.NotifyClose(closeErr)
for {
// 检查是否需要停止监听
select {
case <-closeWatcher:
g.Log().Info(ctx, "停止监听 RabbitMQ 连接状态")
return
default:
}
err := <-closeErr
if err != nil {
g.Log().Errorf(ctx, "RabbitMQ 连接关闭: %v尝试重连...", err)
reconnect(ctx)
mu.RLock()
currentConn := conn
mu.RUnlock()
if currentConn == nil {
return
}
// 创建关闭通知 channel
closeErr := make(chan *amqp.Error, 1)
currentConn.NotifyClose(closeErr)
// 等待连接关闭或停止信号
select {
case err := <-closeErr:
if err != nil {
g.Log().Errorf(ctx, "RabbitMQ 连接关闭: %v尝试重连...", err)
reconnect(ctx)
}
case <-closeWatcher:
g.Log().Info(ctx, "停止监听 RabbitMQ 连接状态")
return
}
}
}
@@ -149,7 +182,7 @@ func reconnect(ctx context.Context) {
}
g.Log().Info(ctx, "RabbitMQ 重连成功")
go handleConnectionClose(ctx)
// 不再重复启动监听 goroutine
return
}
@@ -161,10 +194,17 @@ func Close(ctx context.Context) error {
mu.Lock()
defer mu.Unlock()
// 停止监听 goroutine
if closeWatcher != nil {
close(closeWatcher)
closeWatcher = nil
}
if channel != nil {
if err := channel.Close(); err != nil {
g.Log().Errorf(ctx, "关闭 RabbitMQ Channel 失败: %v", err)
}
channel = nil
}
if conn != nil {
@@ -172,8 +212,10 @@ func Close(ctx context.Context) error {
g.Log().Errorf(ctx, "关闭 RabbitMQ 连接失败: %v", err)
return err
}
conn = nil
}
watcherStarted = false
g.Log().Info(ctx, "RabbitMQ 连接已关闭")
return nil
}