erlang 使用Genserver订阅Phoenix PubSub的正确方法

4dbbbstv  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(183)

我一直在尝试示例化一个genserver进程,它将订阅Phoenix框架中的PubSub,这些是我的文件和错误:
config.ex:

config :excalibur, Excalibur.Endpoint,
  pubsub: [
    adapter: Phoenix.PubSub.PG2,
    name: Excalibur.PubSub
  ]

使用genserver的模块:

defmodule RulesEngine.Router do
  import RulesEngine.Evaluator
  use GenServer
  alias Excalibur.PubSub

  def start_link(_) do
    GenServer.start_link(__MODULE__, name: __MODULE__)
  end

  def init(_) do
    {:ok, {Phoenix.PubSub.subscribe(PubSub, :evaluator)}}
    IO.puts("subscribed")
  end

  # Callbacks

  def handle_info(%{}) do
    IO.puts("received")
  end

  def handle_call({:get, key}, _from, state) do
    {:reply, Map.fetch!(state, key), state}
  end
end

当我进行iex -S混音时,会出现以下错误:

** (Mix) Could not start application excalibur: Excalibur.Application.start(:normal, []) returned an error: shutdown: failed to start child: RulesEngine.Router
    ** (EXIT) an exception was raised:
        ** (FunctionClauseError) no function clause matching in Phoenix.PubSub.subscribe/2
            (phoenix_pubsub 1.1.2) lib/phoenix/pubsub.ex:151: Phoenix.PubSub.subscribe(Excalibur.PubSub, :evaluator)
            (excalibur 0.1.0) lib/rules_engine/router.ex:11: RulesEngine.Router.init/1
            (stdlib 3.12.1) gen_server.erl:374: :gen_server.init_it/2
            (stdlib 3.12.1) gen_server.erl:342: :gen_server.init_it/6
            (stdlib 3.12.1) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

那么,哪种方法是启动订阅PubSub主题的Genserver的正确方法呢?

3htmauhk

3htmauhk1#

根据文档,Phoenix.PubSub.subscribe/3具有以下规范:

@spec subscribe(t(), topic(), keyword()) :: :ok | {:error, term()}

其中@type topic :: binary()。也就是说,您的init/1应该如下所示

def init(_) do
  {:ok, {Phoenix.PubSub.subscribe(PubSub, "evaluator")}}
  |> IO.inspect(label: "subscribed")
end

请注意,我还将IO.puts/1更改为IO.inspect/2以保留返回值。

相关问题