在elixir genstage consumer中使用redis连接

时间:2017-05-09 12:46:52

标签: elixir genstage

我有一个genstage应用程序的例子,在其消费者中我需要使用redis连接。我不明白我需要如何将此连接传递给handle_events。

如果我写:

  defp connection do
    {:ok, conn} = Redix.start_link(host: "0.0.0.0", port: 6379)
    conn
  end

然后每次在handle_events函数内调用连接时,它都会创建一个新连接。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以将conn保留在state消费者的GenStage中(就像您在GenServer中所做的那样,如下所示:

defmodule C do
  use GenStage

  def start_link() do
    GenStage.start_link(C, :ok)
  end

  def init(:ok) do
    {:ok, conn} = Redis.start_link(...)
    {:consumer, conn}
  end

  def handle_events(events, _from, conn) do
    Redix.command!(conn, ...)

    {:noreply, [], conn}
  end
end

这里我在创建消费者时创建连接。您也可以创建更高的连接,如果需要,可以将其传递给它,如下所示:

defmodule C do
  use GenStage

  def start_link(conn) do
    GenStage.start_link(C, conn)
  end

  def init(conn) do
    {:consumer, conn}
  end

  def handle_events(events, _from, conn) do
    Redix.command!(conn, ...)

    {:noreply, [], conn}
  end
end