JavaScriptを有効にしてください

【Elixir】クラスタ内のノードの起動、停止を感知する方法

 ·  ☕ 1 分で読めます

【Elixir】クラスタ内のノードの起動、停止を感知する方法

Elixir でクラスタ構成でクラスタ内のノードの起動、停止を感知する方法

環境

  • Elixir 1.14.2

ノード起動・停止の感知するコード

ノードの起動、停止を実際に感知するコードは以下のようになります。
net_kernel.monitor_nodes/1 を使用してすべてのノードの起動、停止を感知します。

特定のノードのみを感知するなら Node.monitor/2 も使用可能です。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
defmodule ClusterMonitor do
  use GenServer

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

  def init(state) do
    # 全てのノード起動・停止の感知
    :net_kernel.monitor_nodes(true)

    {:ok, state}
  end

  def handle_info({:nodedown, node}, state) do
    # ノード起動
    IO.puts("Node #{node} has stopped.")

    {:noreply, state}
  end

  def handle_info({:nodeup, node}, state) do
    # ノード停止
    IO.puts("Node #{node} has started.")

    {:noreply, state}
  end
end

感知用コードの設定を行います。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
defmodule Demo.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  @impl true
  def start(_type, _args) do
    children = [
      # クラスタ監視
      {ClusterMonitor, name: :cluster_monitor}
    ]

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: Sdm.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

参考

共有

こぴぺたん
著者
こぴぺたん
Copy & Paste Engineer