【问题标题】:How often to connect to RabbitMQ as publisher [duplicate]作为发布者多久连接一次 RabbitMQ [重复]
【发布时间】:2018-12-20 10:13:49
【问题描述】:

我实际上正在关注 RabbitMQ 的教程。我希望我的应用程序的微服务能够通过 RabbitMQ 进行通信。

我创建了一个发布者库,每次我想从 microservice_a 向 microservice_b 发送消息时都会使用它。类似的东西:

sender.go:

// SendEmail ...
func (s *MessageQueue) SendEmail(body string) {
    conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%d", s.Username, s.Password, s.Host, s.Port))
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()

    q, err := ch.QueueDeclare(
        s.QueueName, // name
        true,        // durable
        false,       // delete when unused
        false,       // exclusive
        false,       // no-wait
        nil,         // arguments
    )
    failOnError(err, "Failed to declare a queue")

    err = ch.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "text/plain",
            Body:        []byte(body),
        })
    log.Info(" [x] Sender sent: %s", body)
    failOnError(err, "Failed to publish a message")
}

我只是想知道对于发布者来说,每次发送消息时最好拨打rabbitMQ并关闭RabbitMQ/通道,或者我是否应该创建专用函数。

【问题讨论】:

  • 你在问什么是“最好的”——但这取决于你的应用程序。如果你每秒发送数百条消息,你会发现这种方法根本行不通。如果您每分钟发送 1 条消息,那么这很好。这完全取决于系统的预期运行方式。

标签: go rabbitmq amqp


【解决方案1】:

RabbitMq 连接很昂贵。您实际上应该只为每个实例创建一个。

即使对于频道,我也不建议每次发送消息都创建一个。我建议运行一个专用线程(goroutine)来发布,从 chan 消费。当需要发布时,您的主要逻辑可以推送到 chan。

您可以做到的另一种方法是每个线程有一个通道,以处理您在该线程上需要的任何 rabbitmq 操作。

当然,如果您的发布者是单线程的,最简单的方法是保留所有函数都可以使用的全局 Connection 和 Channel 变量。

还请查看以下答案:

Should I close the channel/connection after every publish?

Whether to create connection every time when amqp.Dial is threadsafe or not in go lang

Is there a performance difference between pooling connections or channels in rabbitmq?

【讨论】:

  • 永远不要合并频道。如果方便的话,只有池连接。当我们谈论成本时,程序员的时间比计算机时间更有价值,所以要考虑一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多