【问题标题】:In Elixir, using a simple_one_for_one supervisor and start_child, how can I set the child's ID in the supervisor?在 Elixir 中,使用 simple_one_for_one 主管和 start_child,我如何在主管中设置孩子的 ID?
【发布时间】:2017-02-21 15:21:55
【问题描述】:

这是一个简单的测试主管:

defmodule SupervisorTest.Worker.Supervisor do
  use Supervisor

  def start_link do
    Supervisor.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def start_worker(args) do
    Supervisor.start_child(__MODULE__, [args])
  end

  def init(:ok) do
    children = [
      worker(SupervisorTest.Worker, [])
    ]

    supervise(children, strategy: :simple_one_for_one)
  end
end

这是我更简单的工人:

defmodule SupervisorTest.Worker do
  use GenServer

  def start_link(args) do
    GenServer.start_link(__MODULE__, args)
  end

  def state(pid) do
    GenServer.call(pid, :state)
  end

  def stop(pid) do
    GenServer.stop(pid, :normal)
  end

  def handle_call(:state, _from, state) do
    {:reply, state, state}
  end
end

理想情况下,我希望能够使用该主管调用Supervisor.which_children 并获取子元组列表,其中 ID 是生成的 UUID。看起来我无法在 init worker 语句中设置它。并且没有start_child/3 可以选择。而且我不能用另一个worker 语句的输出调用start_child/2...所以我看不到任何方法可以将ID 设置为...有什么想法吗?

这段代码写的,当我调用Supervisor.which_children时,每个子元组的第一个元素是:undefined

【问题讨论】:

    标签: elixir erlang-otp


    【解决方案1】:

    你可以在

    中生成UUID
    def start_worker(args) do
      uuid = <generate UUID>,
      Supervisor.start_child(__MODULE__, [args, uuid])
    end
    

    在工人方面:

    def start_link(args, uuid) do
      GenServer.start_link(__MODULE__, [args, uuid])
    end
    
    def init([args,uuid]) do
      {:ok, #State{ uuid: uuid }}
    end
    

    这样,当您获取 which_children 时,您可以通过孩子的 pid 查询孩子的 UUID。

    【讨论】:

      【解决方案2】:

      根据Supervisor.which_children/1superviser:which_children/1 的文档,:simple_one_for_one 主管无法做到这一点:

      id - 在子规范中定义或:undefinedsimple_one_for_one 主管的情况下

      Id - 在子规范中定义或 undefined 用于 simple_one_for_one 主管。

      因此,对于simple_one_for_one 主管,返回的元组的第一项将始终是:undefined

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-09
        • 2017-05-02
        • 2016-06-11
        • 2019-04-27
        • 1970-01-01
        • 2020-08-02
        • 2016-04-20
        • 2021-05-03
        相关资源
        最近更新 更多