0

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.

SandaleRaclette
  • 119
  • 1
  • 12
  • You're asking what is "best" - but that depends upon your application. If you're sending hundreds of messages per second, you'll find that this method won't work at all. If you're sending 1 message per minute, then this is just fine. It all depends upon how the system is intended to operate. – theMayer Jul 12 '18 at 12:47

1 Answers1

0

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?

Tomforge
  • 72
  • 1
  • 8
  • NEVER pool channels. And only pool connections if it is convenient. When we talk about cost, programmer time is infinitely more valuable than computer time, so let that be a consideration. – theMayer Jul 12 '18 at 12:45