一个典型的应用就是rabbitmq项目中rabbit_node_monitor的代码,关于rabbitmq项目,解析:
在下面这段代码里面rabbit_node_monitor是一个gen_server,在它启动的回调函数中,调用了 net_kernel:monitor_nodes(true)方法,同时在handle_info中添加了对nodeup和nodedown消息的处理,这段代码里面在和其它节点建立链接的时候(nodeup)记录了日志,在节点当掉的时候(nodedown)做了数据库和网络的清理
工作,相关的代码文件位置:
- module (rabbit_node_monitor). - behaviour(gen_server). - export([start_link / 0 ]). - export([init / 1 , handle_call / 3 , handle_cast / 2 , handle_info / 2 , terminate / 2 , code_change / 3 ]). - define(SERVER, ?MODULE). %% -- ------------------------------------------------------------------ start_link() -> gen_server:start_link({ local , ?SERVER}, ?MODULE, [], []). %% -- ------------------------------------------------------------------ init([]) -> ok = net_kernel:monitor_nodes( true ), {ok, no_state}. handle_call( _Request , _From , State) -> {noreply, State}. handle_cast( _Msg , State) -> {noreply, State}. handle_info({nodeup, Node}, State) -> rabbit_log:info( " node ~p up " , [Node]), {noreply, State}; handle_info({nodedown, Node}, State) -> rabbit_log:info( " node ~p down " , [Node]), %% TODO: This may turn out to be a performance hog when there are %% lots of nodes. We really only need to execute this code on %% * one * node, rather than all of them. ok = rabbit_networking:on_node_down(Node), ok = rabbit_amqqueue:on_node_down(Node), {noreply, State}; handle_info( _Info , State) -> {noreply, State}. terminate( _Reason , _State ) -> ok. code_change( _OldVsn , State, _Extra ) -> {ok, State}. %% -- ------------------------------------------------------------------ 成功开源项目中可挖掘的东西真是多,特别是学习一个新东西的时候,需要从广泛涉猎一些开源项目,开阔眼界,积累知识,继续!
2012-11-4 17:57:57更新 主动断开节点
Erlang : Disconnect Unwanted Nodes
When you use same cookie for all nodes in a distributed Erlang system, you might have probably seen that all the nodes are interconnected with each other.
(mathu@mathu)>
(mathu@mathu)> nodes().
[mathu9@mathu,mathu1@mathu,mathu2@mathu,mathu3@mathu,
mathu4@mathu,mathu5@mathu,mathu6@mathu,mathu7@mathu,
mathu15@mathu,mathu12@mathu,mathu14@mathu,mathu11@mathu,
mathu10@mathu,mathu13@mathu,mathu8@mathu,mathu9@mathu]
(mathu@mathu)>
Having unwanted nodes connected is overhead for the system. Therefore the bellow one-liner will help to make it clean.
[net_kernel:disconnect(X) || X <- nodes() -- [List_of_wanted_nodes]]. (mathu@mathu)3> [net_kernel:disconnect(X) || X <- nodes() -- [mathu3@mathu, mathu4@mathu]].
[true,true,true,true,true,true,true,true,true,true,true,
true,true]
(mathu@mathu)4> nodes().
[mathu3@mathu,mathu4@mathu]
(mathu@mathu)5>
- Mathuvathanan Mounasmay
与其后面踢掉不如限制可以链接的节点:
allow(Nodes) -> ok | errorTypes:Nodes = [node()]Limits access to the specified set of nodes. Any access attempts made from (or to) nodes not in Nodes will be rejected.Returns error if any element in Nodes is not an atom.
余锋有一篇文章专门介绍: Erlang如何限制节点对集群的访问之net_kernel:allow