0

如果我的 GenStage 的handle_demand/2方法如下所示:

def handle_demand(demand, _state) when demand > 0 do
  case Queue.dequeue do
    nil ->
      Logger.debug("Queue empty.")
      {:noreply, [], []}
    {job, updated_queue} -> {:noreply, job, updated_queue}
  end
end

Queue当我的(GenServer)更改/更新时,如何让它“重新运行” ?

我的队列模块看起来像这样:

defmodule Queue do
  use GenServer

  ### client

  def start_link(state \\ []) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end

  def queue, do: GenServer.call(__MODULE__, :queue)

  def enqueue(value), do: GenServer.cast(__MODULE__, {:enqueue, value})

  def dequeue, do: GenServer.call(__MODULE__, :dequeue)

  ### server

  def init(state), do: {:ok, state}

  def handle_call(:dequeue, _from, [value | state]) do
    {:reply, value, state}
  end

  def handle_call(:dequeue, _from, []), do: {:reply, nil, []}

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

  def handle_cast({:enqueue, value}, state) do
    {:noreply, state ++ [value]}
  end
end
4

1 回答 1

1

为什么要在Queue更改时“重新运行”它?这是对GenStage. 它的发明是为了对抗来自的背压,而不是相反。在现实生活中,您要么根本不需要,要么不想在更新时“重新运行”需求,因为它迟早会通过超时/消息框杀死它。 QueueGenStageQueue

You probably have kinda “consumer” to call handle_demand when it handles the previous load from the queue. GenStage’s repo has four incredibly clear examples using different patterns to work with GenStage. Besides that, there is a great intro to GenStage in Elixir blog.

Just pick up the pattern you need and adopt it from the sources linked above.

于 2017-09-28T06:11:06.293 回答