【问题标题】:How to correctly pass Postgrex.Notifications to a supervisor如何正确地将 Postgrex.Notifications 传递给主管
【发布时间】:2019-12-05 17:36:40
【问题描述】:

我正在尝试在 phoenix 中设置 postgres 触发器。

docs 状态

为了使用它,首先你需要启动通知过程。在您的监督树中:

{Postgrex.Notifications, name: MyApp.Notifications}

这是我的实现:

application.ex

defmodule Foo.Application do
  ...

  def start do
    children = [Foo.Repo, {Postgrex.Notifications, Name: Foo.Notifier}]
    opts = [strategy: :one_for_one, name: Foo.Supervisor]
    Supervisor.start_link(children, ops)
  end
end

notifier.ex

defmodule Foo.Notifier do
  def child_spec(opts) do
    %{
      id: __MODULE__,
      start: {__MODULE__, :start_link, [opts]}
    }
  end

  def start_link(opts \\ []),
    do: GenServer.start_link(__MODULE__, opts)

  def init(opts) do
    # setup postgres listeners
  end
end

我收到一条错误消息说

模块 Postgrex.Notifications 作为子级提供给主管,但它没有实现 child_spec/1。

如果您拥有给定的模块,请定义一个 child_spec/1 函数 它接收一个参数并返回一个子规范作为映射。

但是,如果您不拥有给定的模块并且它没有实现 child_spec/1,而不是直接作为主管传递模块名称 孩子,您必须将孩子规范作为地图传递

所以我按照错误中的示例进行操作

    %{
      id: Postgrex.Notifications,
      start: {Postgrex.Notifications, :start_link, [arg1, arg2]}
    }

我的实现:

children = [
  Foo.Repo,
  %{
    id: Postgrex.Notifications,
    start: {Postgrex.Notifications, :start_link, opts}
  }
]

Supervisor.start_link(children, opts)

但现在我得到了错误

** (Mix) Could not start application survey: exited in: Foo.Application.start(:normal, [])
    ** (EXIT) an exception was raised:
        ** (UndefinedFunctionError) function Supervisor.start_link/1 is undefined or private

【问题讨论】:

    标签: postgresql elixir phoenix


    【解决方案1】:

    我找到this tutorial

    无需将元组传递给主管树,只需传递您的模块并手动调用start_link

    application.ex

    children = [Foo.Repo, Foo.Notifier]
    

    notifier.ex

    @impl true
    def init(opts) do
      with {:ok, _pid, _ref} <- Repo.listen("some_channel_name") do
        {:ok, opts}
      else
        error -> {:stop, error}
      end
    end
    

    repo.ex

    defmodule Foo.Repo do
      def listen(channel) do
        with {:ok, pid} <- Postgrex.Notifications.start_link(__MODULE__.config()),
             {:ok, ref} <- Postgrex.Notifications.listen(pid, channel) do
          {:ok, pid, ref}
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 2019-11-05
      • 2017-06-22
      • 2016-01-08
      • 1970-01-01
      • 2020-02-17
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多