代码之家  ›  专栏  ›  技术社区  ›  Bitwise

从另一个模块使用GenServer

  •  0
  • Bitwise  · 技术社区  · 8 年前

    我有一个简单的GenServer,它是:

    发电机服务器:

    defmodule MyApp.ScoreTableQueue do
      use GenServer
    
      @impl true
      def init(stack) do
        {:ok, stack}
      end
    
      @impl true
      def handle_call(:pop, _from, state) do
        {:reply, state, []}
      end
    
      @impl true
      def handle_cast({:push, item}, state) do
        {:noreply, [item | state]}
      end
    end
    

    模块:

      defp order_score(question, season) do
        for team <- season.teams do
          state = score_table_map(question, team)
    
          # Push state on GenServer queue
        end
    
        create_score_table(question, season)
      end
    
      defp score_table_map(question, team) do
        p_score = Enum.find(team.prediction_scores, &(&1.question_id == question.id))
        %{team_score: p_score.score, team_id: p_score.team_id}
      end
    
      defp create_score_table(question, season) do
        changeset = ScoreTable.changeset(%ScoreTable{
          question_id: question.id,
          season_id: season.id,
          table_details: %{
            information: # Pop state of genserver
          }
        })
    
        Repo.insert(changeset)
      end
    

    正如在代码示例中指出的,我想在GenServer上的循环期间推送一些状态,然后我想在下面的变更集中弹出状态。

    我的主要问题是如何在另一个模块中初始化genserver,这是最佳实践吗?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Justin Wood Yu Hao    8 年前

    您将不希望在另一个模块中初始化GenServer。您需要将其添加到您的监督树中。

    您可能还需要考虑向GenServer模块添加“API”函数,以便它的用户不需要知道它是GenServer。像这样的

    # This assumes you have named your GenServer the same as the module name
    def push(item) do
      GenServer.call(__MODULE__, {:push, item})
    end
    
    def pop() do
      GenServer.call(__MODULE__, :pop)
    end
    

    然后你可以像调用普通函数一样调用它。

    MyApp.ScoreTableQueue.push(:foo)
    stack = MyApp.ScoreTableQueue.pop()
    ...