Golang RabbitMQ 协程建立多个通道:解决 'channel/connection is not open' 错误
这个错误通常发生在以下情况:
- 在建立连接之前,使用了通道。
- 在关闭连接之后,使用了通道。
为了解决这个问题,你需要确保在使用通道之前连接已经建立,并且连接处于打开状态。你可以通过以下代码片段来确保这一点:
conn, err := amqp.Dial('amqp://guest:guest@localhost:5672/')
if err != nil {
panic(err)
}
defer conn.Close()
for i := 0; i < 10; i++ {
ch, err := conn.Channel()
if err != nil {
panic(err)
}
defer ch.Close()
// do something with channel
}
在这个例子中,我们首先创建了一个连接。然后,我们循环创建了 10 个通道。在每次迭代中,我们先检查连接是否打开,然后创建一个新的通道。在每个通道使用完毕后,我们都会关闭它。
请注意,在关闭连接之前,所有的通道都必须关闭。否则,你将收到'channel/connection is not open'的错误提示。
原文地址: https://www.cveoy.top/t/topic/lAeB 著作权归作者所有。请勿转载和采集!