我尝试在 Go 中的单个 channel 上创建多个 AMQP 队列消费者。
我面临的问题是,当创建多个消费者时,如果第一个消费者失败, channel 会立即关闭,从而阻止进一步的操作。
有没有办法避免这种情况,还是我必须重新创建 channel ?
假设队列“client-a”不存在,这将导致在为“client-b”创建队列消费者时出错,因为此时 channel 已关闭。错误将是 Exception (504) Reason: "channel/connection is not open"
package main
import (
"github.com/streadway/amqp"
"log"
)
func check(err error) {
if err != nil {
panic(err)
}
}
func TestChannelProblems() {
// Setup AMQP stuff
connection, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
check(err)
log.Println("Queue connection ok")
channel, err := connection.Channel()
check(err)
log.Println("Queue channel ok")
queuesToConnectTo := []string{"client-a", "client-b"}
for i, _ := range queuesToConnectTo {
queueName := queuesToConnectTo[i]
_, err := channel.Consume(queueName, "", false, false, false, false, nil)
if err != nil {
log.Printf("Connecting to queue %v failed: %v", queueName, err.Error())
}
// ... Here would be the logic to use the return value of channel.Consume
}
}
最佳答案
长话短说:在协议(protocol)异常时关闭 channel 是 AMQP(或至少 RabbitMQ)中的正常行为,必须由应用程序处理。
来源:https://www.rabbitmq.com/channels.html#error-handling
https://stackoverflow.com/questions/58771445/