2 回答
TA贡献1801条经验 获得超15个赞
修改你的func rabbitReceive(queueName string) <-chan string如下:
func rabbitReceive(queueName string) <-chan string {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
q, err := ch.QueueDeclare(
queueName, // name
true, // durable
false, // delete when usused
false, // exclusive
false, // no-waits
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
resCh := make(chan string)
go func() {
d := <-msgs
log.Printf("Received a message: %v from %v", string(d.Body), q.Name)
resCh <- string(d.Body)
conn.Close()
ch.Close()
close(resCh)
}()
return resCh
}
以前的代码导致您出现问题的原因是defer ch.Close(). ch在将响应写入之前关闭resCh。
TA贡献1831条经验 获得超10个赞
跟进 @nightfury1204 很好的答案,你确实ch在写信给resCh. 只有一件事,在 go 例程中你想遍历所有消息,所以更好的方法是:
go func() {
for d := range msgs {
log.Printf("Received a message: %v from %v", string(d.Body), q.Name)
resCh <- string(d.Body)
}
conn.Close()
ch.Close()
close(resCh)
}()
- 2 回答
- 0 关注
- 113 浏览
添加回答
举报