首页 > 解决方案 > 受监督的 genstage 文档上的 genstage 工作人员无法正常工作?

问题描述

https://hexdocs.pm/gen_stage/GenStage.html#module-init-and-subscribe_tosubscribe_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(:正常,[])返回错误:关闭:启动子进程失败:B **(退出)无进程:进程不存在或存在当前没有与给定名称关联的进程,可能是因为它的应用程序没有启动

我的应用程序定义mix.ex

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

有什么我想念的吗?

标签: elixirerlang-supervisorgenstage

解决方案


如果我手动运行它们,它可以工作

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

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

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

defmodule A do
  use GenStage

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

其余的也一样。


推荐阅读