【问题标题】:GenServer implementation of an event handler not handling casts不处理强制转换的事件处理程序的 GenServer 实现
【发布时间】:2019-11-07 22:18:22
【问题描述】:

我试图在我的 Phoenix 应用程序中使用 GenServer 作为 EventBus 的事件处理程序,但由于某种原因,我似乎无法弄清楚为什么没有调用句柄转换函数。我使用: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

【问题讨论】:

    标签: elixir phoenix-framework gen-server


    【解决方案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__)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 2012-09-21
      • 2015-03-17
      相关资源
      最近更新 更多