From ccc3f34fcfd252c84aa544da7724ece0032a17da Mon Sep 17 00:00:00 2001 From: Rafael Ramos Date: Thu, 22 Jul 2021 18:52:51 -0300 Subject: [PATCH] allow connected using connection string --- lib/clients/fake_rabbitmq.ex | 6 +++++- lib/worker/rabbit_connection.ex | 9 +++++++-- test/worker/rabbit_connection_test.exs | 8 ++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/clients/fake_rabbitmq.ex b/lib/clients/fake_rabbitmq.ex index be1a533..7038736 100644 --- a/lib/clients/fake_rabbitmq.ex +++ b/lib/clients/fake_rabbitmq.ex @@ -34,7 +34,7 @@ defmodule ExRabbitPool.FakeRabbitMQ do end @impl true - def open_connection(config) do + def open_connection(config) when is_list(config) do if Keyword.get(config, :queue) == "error.queue" do {:error, :invalid} else @@ -42,6 +42,10 @@ defmodule ExRabbitPool.FakeRabbitMQ do end end + def open_connection(_config) do + {:ok, %Connection{pid: self()}} + end + @impl true def open_channel(conn) do {:ok, %Channel{conn: conn, pid: self()}} diff --git a/lib/worker/rabbit_connection.ex b/lib/worker/rabbit_connection.ex index 14352e3..3e98b51 100644 --- a/lib/worker/rabbit_connection.ex +++ b/lib/worker/rabbit_connection.ex @@ -80,8 +80,10 @@ defmodule ExRabbitPool.Worker.RabbitConnection do # split our opts from the ones passed to the amqp client {opts, amqp_config} = Keyword.split(config, [:adapter]) adapter = Keyword.get(opts, :adapter, ExRabbitPool.RabbitMQ) + uri = amqp_config[:uri] + send(self(), :connect) - {:ok, %State{adapter: adapter, config: amqp_config}} + {:ok, %State{adapter: adapter, config: uri || amqp_config}} end @impl true @@ -188,7 +190,10 @@ defmodule ExRabbitPool.Worker.RabbitConnection do # defaults to `1_000` true = Process.link(pid) - num_channels = Keyword.get(config, :channels, @default_channels) + num_channels = + if Keyword.keyword?(config), + do: Keyword.get(config, :channels, @default_channels), + else: @default_channels channels = do_times(num_channels, 0, fn -> diff --git a/test/worker/rabbit_connection_test.exs b/test/worker/rabbit_connection_test.exs index d46ac6e..46b11dc 100644 --- a/test/worker/rabbit_connection_test.exs +++ b/test/worker/rabbit_connection_test.exs @@ -24,6 +24,14 @@ defmodule ExRabbitPool.Worker.RabbitConnectionTest do assert length(channels) == 5 end + test "creates a connection using uri", %{config: config} do + config = Keyword.put(config, :uri, "amqp://guest:guest@localhost:5672/") + pid = start_supervised!({ConnWorker, config}) + %{channels: channels, connection: connection} = ConnWorker.state(pid) + refute is_nil(connection) + assert length(channels) == 10 + end + test "creates a pool of channels by default", %{config: config} do pid = start_supervised!({ConnWorker, Keyword.delete(config, :channels)}) %{channels: channels} = ConnWorker.state(pid)