defmodule SimpleQueue do
require Logger
require Jason
use GenServer
use AMQP
def start_link(state \\ []) do
GenServer.start_link(__MODULE__, state, name: __MODULE__)
end
def init(chan) do
{:ok, chan}
end
def handle_info(_, {chan, exchange}) do
{:noreply, {chan, exchange}}
end
def handle_call({_ , _}, {chan, exchange}) do
{:reply, {chan, exchange}}
end
def handle_cast({ :push, %{ "service" => s, "method" => m, "args" => a, :uuid => u } }, {chan, exchange}) do
case Jason.encode(%{ "service" => s, "method" => m, "args" => a, :uuid => u }) do
{:ok, json} ->
Logger.info("was sended to rabbit: #{json}")
IO.puts(json)
#AMQP.Basic.publish(chan, exchange, "", json)
{:error, _} ->
Logger.warn("tuple was not encoded")
end
{:noreply, {chan, exchange}}
end
def handle_cast({_ , _}, {chan, exchange}) do
{:noreply, {chan, exchange}}
end
end
You need to have both unique id and name. The id is to tell different children apart within the supervisor, and the name is the locally registered name. For your case you’d have to provide a custom child_spec/1 function. https://hexdocs.pm/elixir/Supervisor.html#module-child_spec-1
if I remove the name from GenServer.start_link() the code does run without errors, but the function “handle_cast({ :push, …}, {chan, exchange})” does not work, messages don’t arrive.
How exactly are you sending messages to the process? I assume via the name, which used to be SimpleQueue?
You now removed the name from the process, as such you need to send the messages explicitly to the PID. But I assume since you spun up the processes under a supervision tree that you don’t have immediate access to said PID.
This begs the question: Why did you want to spawn two instances of SimpleQueue in the first place?
As you noticed names need to be unique, and if you want to send messages to the SimpleQueue via the name then you can (by definition) only send messages to a single process.
It would be helpful if you took a few minutes to write down what exactly you want to accomplish.