Current section
Files
Jump to
Current section
Files
lib/rabbitmq_sender.ex
defmodule RabbitMQSender do
use GenServer
defstruct [:connection, :channel]
# API
def start_link(options \\ []) do
rabbit_options =
case options do
[] -> get_rabbit_options()
_ -> options
end
GenServer.start_link RabbitMQSender, [rabbit_options]
end
@moduledoc """
Documentation for RabbitMQSender.
"""
@doc """
Hello world.
## Examples
iex> RabbitMQSender.hello
:world
"""
def hello do
:world
end
def get_rabbit_options do
Application.get_env(:rabbitmq_sender, :rabbit_options, [])
end
def send_message(server, queue, message) do
server |> GenServer.cast({:send_message, queue, message})
end
# Callbacks
def init([rabbit_options]) do
{:ok, connection} = AMQP.Connection.open(rabbit_options)
{:ok, channel} = AMQP.Channel.open(connection)
{:ok, %RabbitMQSender{connection: connection, channel: channel}}
end
def handle_cast({:send_message, queue, message}, %RabbitMQSender{connection: connection, channel: channel} = state) do
AMQP.Queue.declare(channel, queue)
AMQP.Basic.publish(channel, "", queue, message)
IO.puts "Message #{message} has been sent to #{queue}"
{:noreply, state}
end
end