Run rabbitmq in other process

Hello, I use rabbitmq to make a messaging architecture, one of my component need to be on elixir. But when I need to test something for example a database, I try to do it with command iex -S mix but when I do it, rabbitmq is start(waiting messages) and I can’t type anything. If I comment everything related with rabbit, I can write to db and else.
So how to do that when I compile my project all start right(rabbitmq wait messages), but when I run iex -S mix my rabbitmq didn’t start.

defmodule Receive do
  use MethodMissing

  def wait_for_messages do
    receive do
      {:basic_deliver, payload, meta} ->
        IO.puts " [x] Received #{payload}"

        Original_File.save_data(payload)

        wait_for_messages()
    end
  end
end


defmodule Repo do
  use Ecto.Repo,
    otp_app: :dispatcher_service,
    adapter: Mongo.Ecto
end


defmodule Original_File do
  use Ecto.Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "original_file" do
    field :original_filename
    field :file_url
    field :supported
    field :filetype
    field :filename
    # field :metadata, :map
    #field :versions, type: Hash
  end
  def save_data(payload) do
    payload = Poison.decode!(~s(#{payload}))
    IO.inspect payload["payload"]["uuid"]
    original_file = %Original_File{id: payload["payload"]["uuid"], original_filename: payload["payload"]["original_filename"]}
    IO.inspect original_file
  end
end



{:ok, connection} = AMQP.Connection.open
{:ok, channel} = AMQP.Channel.open(connection)
AMQP.Queue.declare(channel, "result", durable: true)
AMQP.Basic.consume(channel, "result", nil, no_ack: true)
AMQP.Exchange.declare(channel, "exchange", :topic, durable: true)

IO.puts " [*] Waiting for messages. To exit press CTRL+C"

Receive.wait_for_messages

spawn(fn ->
  {:ok, connection} = AMQP.Connection.open
  {:ok, channel} = AMQP.Channel.open(connection)
  AMQP.Queue.declare(channel, "result", durable: true)
  AMQP.Basic.consume(channel, "result", nil, no_ack: true)
  AMQP.Exchange.declare(channel, "exchange", :topic, durable: true)

  IO.puts " [*] Waiting for messages."

  Receive.wait_for_messages
end)

receive blocks until it receives. By spawn/1ing your rabbitmq looper in another process, you can keep the main IEx process available to tinker.

3 Likes

U r just my savior, thanks a lot!