2017-09-07 93 views
0

我正在使用GenServer作爲排隊系統。我怎樣才能使整個應用程序訪問相同的過程?如何爲我的整個應用程序提供GenServer進程?

我想過把它application.ex將做到這一點,就像這樣:

children = [ 
    supervisor(Prefect, [], name: PrefectQueue) 
] 

Prefect模塊是GenServer:

defmodule Prefect do 
    use GenServer 
    alias Prefect.Document 

    # client 
    def start_link() do 
    GenServer.start_link(__MODULE__, []) 
    end 

    def add(pid, item) do 
    GenServer.cast(pid, item) 
    end 

    # server 
    def handle_cast(item, list) do 
    updated_list = [item | list] 
    {:noreply, updated_list} 
    end 
end 

我似乎無法訪問我的控制器,雖然:

defmodule PrefectWeb.DocumentController do 
    use PrefectWeb, :controller 

    def create(conn, params) do 
    Prefect.add(PrefectQueue, params["id"]) 
    conn 
    |> send_resp(200, "Queued #{Prefect.view(PrefectQueue)}") 
    end 
end 

發佈到該創建函數給出此錯誤:

[info] POST /api/documents 
[debug] Processing with PrefectWeb.DocumentController.create/2 
    Parameters: %{"id" => "1"} 
    Pipelines: [:api] 
[error] #PID<0.349.0> running PrefectWeb.Endpoint terminated 
Server: 0.0.0.0:4000 (http) 
Request: POST /api/documents 
** (exit) exited in: GenServer.call(Prefect.Queue, :view, 5000) 
    ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started 
+0

您正在使用'Prefect.view(PrefectQueue)',但我無法在'Prefect'模塊中找到它。你確定,你提供的代碼對應於給定的錯誤嗎? –

+0

這是application.ex中進程的名稱:'supervisor(Prefect,[],name:PrefectQueue)''。不應該那樣工作? –

回答

2

您必須在GenServer本身命名進程,而不是通過supervisor子級列表。請嘗試:

defmodule Prefect do 
    use GenServer 
    alias Prefect.Document 

    # client 
    def start_link() do 
    GenServer.start_link(__MODULE__, [], name: __MODULE__) 
    end 

    def add(pid, item) do 
    GenServer.cast(pid, item) 
    end 

    # server 
    def handle_cast(item, list) do 
    updated_list = [item | list] 
    {:noreply, updated_list} 
    end 
end 

您的過程現在應該像這樣調用Prefect.view(Prefect)

相關問題