2017-05-09 45 views
1

我有一個genstage應用程序的例子,在它的消費者中,我需要使用redis的連接。我不明白我需要如何將此連接傳遞給handle_events。在elixir公共消費者階段使用redis連接

如果我寫:

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

然後在每次連接被稱爲handle_events函數裏面的時候,它會創建一個新的連接。

我該如何解決這個問題?

回答

0

你可以保持connGenStage消費者(就像你在一個GenServer,像這樣的state

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