peppy

peppy

Help: How to use AMQP channel from pool for publishing messages?

I set up a small process that maintains an AMQP connection/channel. This script automatically reconnects to RabbitMQ if the connection fails. I built this based on an old, depreciated and incomplete guide. I’m still a newbie, so I don’t fully understand how to use this. I know the script is connecting and reconnecting (as far as I know), but how do I actually use/fetch the channel?

For example, if I have a function in a different module, such as chatroom.ex, how do I fetch the existing channel in the pool so that I can publish messages to a queue?

def publish_function(chatmessage) do
   # Receive a chat room message here and publish it to "test_queue" in RabbitMQ. How do I use the existing connections?
   #something like:
  channel = ???? #channel in the consumer module?
  AMQP.Basic.publish(*channel*, "", "test_queue", chatmessage)

end

Here is what I have so far:

connectionmanager.ex:

defmodule ExchatWeb.AMQPConnectionManager do

  use GenServer
  use AMQP

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, :ok, [name: __MODULE__])
  end

  def init(:ok) do
    children = [
      ExchatWeb.Publish
    ]

    Supervisor.start_link(children, strategy: :one_for_one, name: ExchatWeb.PublishSupervisor)
    establish_new_connection()
  end

  defp establish_new_connection do
    case AMQP.Connection.open do
      {:ok, conn} ->
        Process.link conn.pid
        {:ok, {conn, %{}}}
      {:error, reason} ->
        IO.puts "failed for #{inspect reason}"
        :timer.sleep 5000
        establish_new_connection()
    end
  end

  def request_channel(consumer) do
    GenServer.cast(__MODULE__, {:chan_request, consumer})
  end

  def handle_cast({:chan_request, consumer}, {conn, channel_mappings}) do
    new_mapping = store_channel_mapping(conn, consumer, channel_mappings)
    channel = Map.get(new_mapping, consumer)
    consumer.channel_available(channel)
    {:noreply, {conn, new_mapping}}
  end

  defp store_channel_mapping(conn, consumer, channel_mappings) do
    Map.put_new_lazy(channel_mappings, consumer, fn() -> create_channel(conn) end)
    IO.inspect(channel_mappings)
  end

  defp create_channel(conn) do
    {:ok, chan} = Channel.open(conn)
    chan
  end

end

publishconsumer.ex:

defmodule ExchatWeb.PublishConsumer do
  use GenServer

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, :ok, [name: __MODULE__])
  end

  def init(_opts) do
    ExchatWeb.AMQPConnectionManager.request_channel(__MODULE__)
    {:ok, nil}
  end

  def channel_available(chan) do
    GenServer.cast(__MODULE__, {:channel_available, chan})
  end

  def handle_cast({:channel_available, chan}, _state) do
    IO.inspect(chan)
    #bind_to_queue chan
    {:noreply, chan}
  end

end

Most Liked

beepbeepbopbop

beepbeepbopbop

If I am reading this correctly, you want to checkout a channel from your connection pool and publish to said channel. Based off the code you’ve posted, I assume the following:

  • Your connection pool abstraction is using a process (although I would use something like Poolboy)
  • You need a method akin to ConnectionManager.checkout(...) which results in getting a channel that you can use.

In this instance, user land code may look like this:

def publish_msg(msg) do
  channel = ConnectionManager.checkout()
  AMQP.Basic.publish(channel, "", "test_queue", msg)
  # Check the connection back in.
end

This means that while ConnectionManager is a process, you need to change it to use a synchronous API, using the call() variants. You would also need to implement your check-in logic, unless you use a callback API where it automatically cleans up for you.

def callback_example(msg) do
  ConnectionManager.with_channel(fn channel ->
    AMQP.Basic.publish(channel, "", "test_queue", msg)
    # Check-ins are implicit.
  end)
end

Your handle_cast simply will not work as it is now. Since your user land code assumes that a channel is something that you return, you can’t use a handle_cast, unless you utilise GenServer.reply, which isn’t necessary in your use case.

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New

Other popular topics Top

axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31013 112
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

We're in Beta

About us Mission Statement