Golang 中的事件驱动模型

Event driven model in Golang

我正在阅读 RabbitMQ tutorial 并看到以下代码:

forever := make(chan bool)

go func() {
  for d := range msgs {
    log.Printf("Received a message: %s", d.Body)
  }
}()

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever

我感兴趣的是for d := range msgs。这个for循环是如何处理事件的?例如。在应用程序启动时,msgs 队列缓冲区中只有一条消息。

问题:

  1. 它将如何处理下一个事件?
  2. playing around 使用此代码后,我发现它可能卡在 log.Printf 行并且不再处理事件。可能是什么原因?
  1. How would it process next event?

除了对基本数据结构进行迭代外,GoLang 中的 range 还可以对从通道接收的值进行迭代。 Range 在从队列接收到每个元素时对其进行迭代,并且仅在通道关闭时结束。 下一次迭代将在通道 (msgs) 收到一个值时发生

msgs <- message
  1. After some playing around with this code I found that it could stuck on log.Printf line and wouldn't process events anymore. What can be a reason?

考虑到有一个 blocking channel forever 并且我们有一个遍历 msgs 通道的范围,因此有 2 个可能的预期操作:

或者

  1. 通过消息通道发送消息

    消息 <- 消息

  1. 将值发送到 forever 以便解除对进程的阻塞

    永远 <- false

似乎该解决方案旨在等待并通过通道异步处理消息。