用Genserver订阅Phoenix PubSub的正确方法。

问题描述 投票:0回答:1

我一直在尝试在Phoenix框架中实例化一个能订阅PubSub的genserver进程,这些是我的文件和错误。

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时,就会发生这个错误。

** (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

那么,哪种方式才是正确的旋转Genserver来订阅PubSub主题的方法呢?

erlang elixir phoenix
1个回答
2
投票

如同文档中所说的那样。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/1IO.inspect/2 以保存返回值。

© www.soinside.com 2019 - 2024. All rights reserved.