【发布时间】:2021-05-07 10:38:11
【问题描述】:
我在图书馆中有这个 GenServer:
defmodule MyLib.Cache do
use GenServer
def start_link([]) do
IO.puts("****cache genserver, name: #{__MODULE__}")
# GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
GenServer.start_link(__MODULE__, %{}, name: MyLibCache) # no dot
end
# [.........]
还有这个应用程序:
defmodule MyApp.Application do
use Application
def start(_type, _args) do
import Supervisor.Spec
children = [
{Phoenix.PubSub, [name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2]},
{MyLib.Repo, []},
{MyAppWeb.Endpoint, []},
{MyLib.Cache, []} # notice the dot
]
-
为什么当我指定名称时它可以工作:
MyLibCache(不带点)虽然名称必须是MyLib.Cache- 带点? -
我希望能够在 GenServer 中使用
name: __MODULE__。但是有了它,它将无法在application.ex中启动它,因为它不会找到具有这样名称的模块。如何解决?
更新:
运行时出错,仅当我尝试访问调用缓存的页面时,即不在启动时:
exited in: GenServer.call(MyLibCache, {:get, "Elixir.MyLib.Dal.User.2"}, 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
也就是说,这将不会出错:
GenServer.start_link(__MODULE__, %{}, name: MyLibCache)
# or
# GenServer.start_link(__MODULE__, %{}, name: MyLib.Cache) # with dot
this - 上面显示的错误:
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
【问题讨论】:
标签: elixir gen-server