RMQ v0.4.0 RMQ.Connection behaviour View Source

A GenServer which provides a robust connection to the RabbitMQ server.

Usage

iex> RMQ.Connection.start_link([])
{:ok, #PID<0.310.0>}
iex> RMQ.Connection.get_connection()
{:ok, %AMQP.Connection{pid: #PID<0.314.0>}}

Configuration

config :rmq, :connection,
  uri: "amqp://localhost",
  name: "MyAppConnection",
  reconnect_interval: 5000,
  username: "user",
  password: "password"
  # ... other options for AMQP.Connection.open/3

All configuration is optional.

  • :uri - an AMQP URI. Defaults to "amqp://localhost";
  • :reconnect_interval - a reconnect interval in milliseconds. It can be also a function that accepts the current connection attempt as a number and returns a new interval. Defaults to 5000;
  • other options for AMQP.Connection.open/2.

Dynamic configuration

In case you need to read the configuration dynamically you can use config/0 callback:

defmodule MyApp.RabbitConnection do
  use RMQ.Connection

  def config do
    [
      uri: System.get_env("RABBITMQ_URI"),
      name: "MyAppConnection",
      reconnect_interval: fn attempt -> attempt * 1000 end
      # ...
    ]
  end
end

Multiple connections

If for some reason, you need to hold multiple connections you can use the following approach:

defmodule MyApp.RabbitConnection1 do
  use RMQ.Connection, otp_app: :my_app
end

defmodule MyApp.RabbitConnection2 do
  use RMQ.Connection, otp_app: :my_app
end

# config.exs
config :my_app, MyApp.RabbitConnection1,
  uri: "amqp://localhost",
  name: "MyAppConnection1"

config :my_app, MyApp.RabbitConnection2,
  uri: "amqp://localhost",
  name: "MyAppConnection2"

otp_app: :my_app here can be omitted and in that case otp_app: :rmq will be used.

Link to this section Summary

Functions

Returns a specification to start this module under a supervisor.

Returns the configuration.

Starts a GenServer process linked to the current process.

Starts a GenServer process linked to the current process.

Callbacks

A callback invoked right before connection.

Link to this section Functions

Returns a specification to start this module under a supervisor.

See Supervisor.

Returns the configuration.

Link to this function

get_connection(module \\ __MODULE__)

View Source

Specs

get_connection(module :: module()) ::
  {:ok, AMQP.Connection.t()} | {:error, :not_connected}

Gets the connection.

Starts a GenServer process linked to the current process.

Link to this function

start_link(module, opts)

View Source

Starts a GenServer process linked to the current process.

Link to this section Callbacks

Specs

config() :: keyword()

A callback invoked right before connection.

use RMQ.Connection will inject the default implementation of it:

def config do
  Application.get_env(@otp_app, __MODULE__, [])
end

What can be eventually overridden into something like:

def config do
  Keyword.merge(super(), uri: System.get_env("RABBITMQ_URI"))
end