首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地将Postgrex.Notifications传递给主管

如何正确地将Postgrex.Notifications传递给主管
EN

Stack Overflow用户
提问于 2019-12-05 04:03:44
回答 1查看 279关注 0票数 0

我想在凤凰城设置postgres触发器。

文档状态

为了使用它,首先需要启动通知过程。在你的监管树上: {Postgrex.Notifications, name: MyApp.Notifications}

下面是我的实现:

application.ex

代码语言:javascript
复制
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

代码语言:javascript
复制
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。 如果您拥有给定的模块,请定义一个子_spec/1函数,该函数接收参数并将子规范作为映射返回。 但是,如果您不拥有给定的模块,并且它没有实现子规范/1,而不是将模块名直接作为主管子传递,则必须将子规范作为映射传递。

所以我遵循了错误中的例子

代码语言:javascript
复制
    %{
      id: Postgrex.Notifications,
      start: {Postgrex.Notifications, :start_link, [arg1, arg2]}
    }

我的实施:

代码语言:javascript
复制
children = [
  Foo.Repo,
  %{
    id: Postgrex.Notifications,
    start: {Postgrex.Notifications, :start_link, opts}
  }
]

Supervisor.start_link(children, opts)

但现在我明白了

代码语言:javascript
复制
** (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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-05 09:36:40

我找到了本教程

与其将元组传递给主管树,不如传递模块并手动调用start_link

application.ex

代码语言:javascript
复制
children = [Foo.Repo, Foo.Notifier]

notifier.ex

代码语言:javascript
复制
@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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59188077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档