【发布时间】:2021-11-25 22:31:57
【问题描述】:
我在 Golang 上使用 RabbitMQ,我发现自己遇到了一些以前从未遇到过的麻烦。在一个Publish 之后,连接会一直关闭。这是sn-p:
func (k*K) DoWork(){
[...]
go func() {
for {
time.Sleep(time.Second * 5)
k.eventLock.Lock()
if !k.connected {
fmt.Printf("Not connected, skip\n")
k.eventLock.Unlock()
continue
}
k.eventLock.Unlock()
err = k.outChannel.Publish(k.outExchangeName, "", true, true, amqp.Publishing{
ContentType: "application/json",
Body: content,
})
if err != nil {
fmt.Printf("Error sending status - %v\n", err)
for {
err = k.initOutConnection()
if err != nil {
fmt.Printf("An error occurred initOut - %v\n", err)
} else {
fmt.Printf("Restablished connection\n")
break
}
}
continue
} else {
fmt.Printf("Sent keep alive\n")
}
}
}()
}
func (k *K) initOutConnection() error {
var err error
k.outConnection, err = k.getRabbitConnection()
if err != nil {
return err
}
k.outChannel, err = k.outConnection.Channel()
if err != nil {
return err
}
k.outExchangeName = os.Getenv("RABBIT_MQ_OUT_EXCHANGE_NAME")
err = k.outChannel.ExchangeDeclare(
k.outExchangeName,
"fanout",
true,
true,
false,
true, nil)
if err != nil {
return err
}
return nil
}
这是输出:
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
Sent keep alive
Error sending status - Exception (504) Reason: "channel/connection is not open"
Restablished connection
这是一个完美的循环,一次发送成功,连接关闭,我建立连接,然后又一次成功,一次失败。但这在生产者应用程序看来,消费者没有收到任何消息。
如果我在一次发布后故意关闭连接,它确实有效:
err = k.outChannel.Publish()
if err == nil {
k.outChannel.Close()
k.initOutConnection()
fmt.Printf("Sent keep alive\n")
}
它产生一致的输出:
Sent keep alive
Sent keep alive
Sent keep alive
但是我想为我的所有publish 使用一个连接,有人知道我做错了什么吗?
【问题讨论】:
标签: go networking rabbitmq amqp