Golang RabbitMQ: 创建多个通道,解决 'channel/connection is not open' 错误
这个错误提示通常是因为 RabbitMQ 连接或通道未正确打开导致的。以下是建立多个通道的示例代码,可以帮助您解决此问题:
package main
import (
"fmt"
"log"
"github.com/streadway/amqp"
)
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("failed to connect to RabbitMQ: %v", err)
}
defer conn.Close()
done := make(chan bool)
go func() {
for i := 1; i <= 5; i++ {
ch, err := conn.Channel()
if err != nil {
log.Fatalf("failed to open a channel: %v", err)
}
defer ch.Close()
queue := fmt.Sprintf("queue-%d", i)
if _, err := ch.QueueDeclare(queue, false, false, false, false, nil); err != nil {
log.Fatalf("failed to declare queue %s: %v", queue, err)
}
log.Printf("channel %d created and queue %s declared", i, queue)
}
done <- true
}()
<-done
log.Println("all channels created successfully")
}
在上面的示例中,我们通过amqp.Dial函数建立了与 RabbitMQ 的连接。然后,我们启动了一个协程,在其中打开 5 个通道,并为每个通道声明一个队列。请注意,我们使用defer语句在每个通道关闭时关闭通道。最后,我们使用一个无缓冲通道(done)来等待所有通道都成功创建,然后我们记录成功消息。
希望这可以帮助您解决您的问题!
原文地址: https://www.cveoy.top/t/topic/lAeL 著作权归作者所有。请勿转载和采集!