erlang 如何实现通知一个节点另一个节点是否退出的功能

l2osamch  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(153)

我正在创建一个节点群集,我希望在每次节点连接或未连接时都能得到通知,这怎么可能呢?

jckbn6z7

jckbn6z71#

Create a gen_server and call net_kernel:monitor_nodes(true) in the init method. Now the gen_server will receive {node_up, Node} and {node_down, Node} messages whenever a node joins or leaves the cluster.

-module(node_monitor).

-behaviour(gen_server).

%% export API
-export([start_link/0,
     stop/0
    ]).

%% export gen_server callbacks
-export([init/1,
     handle_call/3,
     handle_cast/2,
     handle_info/2,
     terminate/2,
     code_change/3]).

-record(state, {}).

-define(SERVER_NAME, ?MODULE).
%%====================================
%% API
%%====================================
start_link() ->
    gen_server:start_link({local, ?SERVER_NAME}, ?MODULE, [], []).

stop() ->
    gen_server:cast(?SERVER_NAME, stop).

%%====================================
%% callbacks
%%====================================
init([]) ->
    net_kernel:monitor_nodes(true),
    {ok, #state{}}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

handle_info({nodeup, _Node} = Event, State) ->
%%TODO: do something here
    {noreply, State};

handle_info({nodedown, _Node} = Event, State) ->
  %%TODO: do something here
    {noreply, State};

handle_info(_Msg, State) ->
    {noreply, State}.

handle_cast(stop, State) ->
    {stop, normal, State};
handle_cast(_Msg, State) ->
    {noreply, State}.

handle_call(_Msg, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

A word of caution though, all the nodes will receive these notifications. So if only one node per cluster should be handling node_up and node_down notifications, that logic needs to be implemented on top of this gen_server.

相关问题