受监督的genstage文档工作者无法正常工作?

时间:2018-06-26 08:07:53

标签: elixir supervisor genstage

https://hexdocs.pm/gen_stage/GenStage.html#module-init-and-subscribe_to,我用subscribe_to选项定义了GenStage模块

defmodule A do
  use GenStage

  def start_link(number) do
    GenStage.start_link(A, number)
  end

  def init(counter) do
    {:producer, counter}
  end

  def handle_demand(demand, counter) when demand > 0 do
    # If the counter is 3 and we ask for 2 items, we will
    # emit the items 3 and 4, and set the state to 5.
    events = Enum.to_list(counter..counter+demand-1)
    {:noreply, events, counter + demand}
  end
end

defmodule B do
  use GenStage

  def start_link(number) do
    GenStage.start_link(B, number)
  end

  def init(number) do
    {:producer_consumer, number, subscribe_to: [{A, max_demand: 10}]}
  end

  def handle_events(events, _from, number) do
    events = Enum.map(events, & &1 * number)
    {:noreply, events, number}
  end
end

defmodule C do
  use GenStage

  def start_link() do
    GenStage.start_link(C, :ok)
  end

  def init(:ok) do
    {:consumer, :the_state_does_not_matter, subscribe_to: [B]}
  end

  def handle_events(events, _from, state) do
    # Wait for a second.
    Process.sleep(1000)

    # Inspect the events.
    IO.inspect(events)

    # We are a consumer, so we would never emit items.
    {:noreply, [], state}
  end
end

如果我手动运行它们,它将起作用

iex(1)> GenStage.start_link(A, 0, name: A)
{:ok, #PID<0.195.0>}
iex(2)> GenStage.start_link(B, 2, name: B)
{:ok, #PID<0.197.0>}
iex(3)> GenStage.start_link(C, :ok)
{:ok, #PID<0.199.0>}
[0, 2, 4, 6, 8]
[10, 12, 14, 16, 18]
[20, 22, 24, 26, 28]
[30, 32, 34, 36, 38]
‘(*,.0’

然后建议将其添加到主管树中:

  

在监督树中,通常是通过启动多个   工人:

defmodule TestDep.Application do
  @moduledoc false

  use Application

  def start(_type, _args) do
    import Supervisor.Spec

    children = [
      worker(A, [0]),
      worker(B, [2]),
      worker(C, []),
    ]
    opts = [strategy: :rest_for_one]
    Supervisor.start_link(children, opts)
  end
end

那是我的主管树,但是当使用iex -S mix运行应用程序时,我收到:

  

**(混合)无法启动应用程序testdep:TestDep.Application.start(:n​​ormal,[])返回错误:关机:   无法启动孩子:B   **(EXIT)无进程:该进程尚未运行或当前没有与该给定名称相关联的进程,可能是因为   应用程序未启动

我的应用在mix.ex上的定义为

def application do
[
extra_applications: [:logger],
mod: {TestDep.Application, []}
]
end

有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

  

如果我手动运行它们,它将起作用

它不是:( 有效的不是您要测试的东西,也不等同于您在监督树中开始的工作,这是:

A.start_link(0)
B.start_link(2)
C.start_link()

也就是说,您可能希望将名称传递给包装的GenStage.start_link

defmodule A do
  use GenStage

  def start_link(number) do
    #                            ⇓⇓⇓⇓⇓⇓⇓⇓⇓ THIS
    GenStage.start_link(A, number, name: A)
  end

其余的都一样。