Skip to content

messaging

Benjamin Bennett edited this page Dec 13, 2020 · 15 revisions

This is a simple implementation of message publishing using RabbitMQ and a Go RabbitMQ Client Library.

cd go-bits/messaging
docker-compose up
go run -race main.go
  1. A connection manager is created and handles:
    • Initial connection to RabbitMQ and automated re-connection if the connection is closed.
    • Obtaining a server channel (not to be confused with a go channel).
  2. Connection to RabbitMQ is initiated.
  3. A queue is configured.
  4. A message publisher is created.
  5. Loop is used to publish messages.

Create Connection Manager

Configuration for the connection manager is passed to NewConnManager and used to set:

  • The address for RabbitMQ.
  • The retry interval.
  • The maximum number of retry attempts.

Initiate Connection

  1. A new connection is created on the connection manager struct by calling dial().
  2. NotifyClose registers a listener (a channel of *amqp.Error) and assigns it to notifyConnClose on the connection manager struct.
    • If the connection is closed normally, the channel will be closed.
    • If there is a connection error, the channel will receive a pointer to an Error.
  3. A go routine is started to handle reconnecting to RabbitMQ if the connection is closed.

Handle Reconnection

  1. The reconnect func blocks waiting for context cancellation or
  2. for a connection error, or for the connection to be closed.
  3. The number of retries relative to the maximum permitted number of retries is checked.
  4. The dial func is called to attempt to establish a connection.
  5. If dial returns an error then the process blocks until context is cancelled or
  6. the retry interval has passed.
  7. If the connection is successful then NotifyClose is called (see above)
  8. and reconnect calls itself.
  1. A channel is obtained from the connection.
  2. An exchange is declared.
  3. A queue is declared.
  4. The queue is then bound to the exchange.

Create Publisher

  • NewPublisher returns a pointer to a populated struct.

Publish Message

  1. A channel is obtained from the connection.
  2. Confirm puts the channel in confirm mode in order to verify that all messages have been successfully received by the server.
  3. A message is published on the channel.
  4. The select blocks until either the publishing is confirmed and acknowledged or a timeout has been triggered waiting for the notification and confirmation.