我使用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 :(得分:3)
您必须在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)
一样调用您的流程。