以发布者身份连接到RabbitMQ的频率[重复]

I'm actually following the RabbitMQ's tutorials. I want the microservices of my application be able to communicate through RabbitMQ.

I create a publisher lib that I use each time I want to send a message to a microservice_b from a microservice_a. Something like :

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")
}

I just want to know in the case of a publisher if it's best to dial the rabbitMQ and close the RabbitMQ/channel each time I send a message as now, or if I should create dedicated functions to.

</div>

RabbitMq connections are expensive. You should really only create one per instance.

Even for channels I wouldn't recommend creating one per message send. I suggest running a dedicated thread (goroutine) for publishing, consuming from a chan. Your main logic can then push to the chan when publishing is required.

Another way you could do it is to have one channel per thread, to handle whatever rabbitmq operations you require on that thread.

Of course, if your publisher is single threaded, the simplest way will be to keep a global Connection and Channel variable that all your functions can use.

Also check out these answers:

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?