GenServer实现的事件处理程序不处理强制转换

时间:2019-06-26 03:40:23

标签: elixir phoenix-framework gen-server

我试图在我的Phoenix应用程序中将GenServer用作EventBus的事件处理程序,但是由于某些原因,我似乎无法弄清为什么未调用handle cast函数。我通过:observer.start()检查了该过程是否仍然有效。

GenServer是否缺少某些东西来正确处理转换调用?

基本上,过程函数应该处理传入的事件并将其强制转换为GenServer,其中GenServer将处理强制转换并对该事件执行域逻辑。

---- Gen服务器模块----

defmodule App.Notifications.EventHandler do
  use GenServer
  require Logger


  def start_link(opts \\ []) do
    {:ok, pid} = GenServer.start_link(__MODULE__, [], opts)
  end

  def init([]) do
    {:ok, []}
  end

  def process({topic_id, event_id}) do
    Logger.info("event notification process recieved!!") <---- THIS IS GETTING PRINTED!

    GenServer.cast(__MODULE__, {topic_id, event_id})
  end



def handle_cast({topic_id, event_id}, state) do
  Logger.info("event  notification data Recieved!!") <----- THIS IS NOT

  # do stuff

  {:noreply, state}
end


end

----应用程序模块-----

defmodule App.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application


  def start(_type, _args) do

    EventBus.subscribe({App.Notifications.EventHandler, ["^event_notification_created$"]})

    # List all child processes to be supervised
    children = [
      # Start the Ecto repository
      App.Repo,
      # Start the endpoint when the application starts
      AppWeb.Endpoint,
      # Starts a worker by calling: App.Worker.start_link(arg)
      # {App.Worker, arg},,
      App.Notifications.EventHandler <--- STARTING THE GEN SERVER HERE
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: App.Supervisor]
    Supervisor.start_link(children, opts)
  end

  # Tell Phoenix to update the endpoint configuration
  # whenever the application is updated.
  def config_change(changed, _new, removed) do
    App.Endpoint.config_change(changed, removed)
    :ok
  end
end

1 个答案:

答案 0 :(得分:1)

GenServer.cast/2上的文档指出,调用GenServer.cast/2的第一个参数必须为server()类型,即:

  

此模块的文档“ Name registration”部分中描述的任何值。

在您的代码中,启动未命名的链接:

GenServer.start_link(__MODULE__, [], opts)

但是您将其强制转换为命名为GenServer

#              ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
GenServer.cast(__MODULE__, {topic_id, event_id})

最简单的解决方法,启动名为:

的服务器
GenServer.start_link(__MODULE__, [], name: __MODULE__)