Erlang分布式节点中的注册进程使用实例(erlang file)干货满满

随心笔谈11个月前发布 admin
97 0



上一篇文章中说到, 注册进程关联的原子具有全局作用域, 这里的全局指的是当前 Erlang 虚拟机, 在分布式中, 便是当前分布式节点. 因此, 在一个节点中注册进程关联的原子, 在另一个节点中是不能直接使用, 而必须配和目标节点使用.

复制代码 代码如下:

{RegName, Node} ! {messages}.

例子

先启动一个 Server 节点

复制代码 代码如下:

erl -sname server

然后在 Erlang Shell 中操作

先简单介绍几个常用函数

复制代码 代码如下:

% 查看当前节点

node().

%=> ‘server@Gentoo-PC’

% 查看所有已连接的节点

nodes().

%=> []                                        % 此时还未连接其它节点

% 查看当前节点是否存活

is_alive().

%=> true

然后进入正题

复制代码 代码如下:

% 启动上一篇文章中最后的那个程序

test:start().

% Waiting for new message.

%=> true

% 当前节点可以使用 testp 原子

testp ! message.

% New message: message

% Waiting for new message.

%=> message

然后启动另外一个 Client 节点

复制代码 代码如下:

erl -sname client

在新的 Erlang Shell 中

复制代码 代码如下:

nodes().

%=> []                                         % 此时未连接节点

% 当前节点无法直接使用这个原子的

testp ! {}.

% ** exception error: bad argument

%      in operator  !/2

%         called as testp ! {}

% 需要配合目标节点一起使用

{testp, ‘server@Gentoo-PC’} ! {}.

%=> {}                                         % 语句返回值

此时, server 节点就会接收到消息, 并打印出

复制代码 代码如下:

% New message: {}

% Waiting for new message.

节点间首次连接后, 两个节点将会保持连接

在 Client 节点中

复制代码 代码如下:

nodes().

%=> [‘server@Gentoo-PC’]

在 Server 节点中

复制代码 代码如下:

nodes().

%=> [‘client@Gentoo-PC’]

结尾

当然, 这只是个方法, 由于在模块中定义了 call 函数包裹了起来, 所以可以使用远程调用, 调用 Server 节点上的 test:call 方法.

可以使用 rpc 模块中的 call/4 方法远程调用函数

复制代码 代码如下:

% 在 Node 节点上执行 apply(Module, Function, Args)

% 调用成功时返回 Result, 调用失败时返回 {badrpc, Reason}

-spec rpc:call(Node, Module, Function, Args} -> Result | {badrpc, Reason}

在 Client 节点中

复制代码 代码如下:

rpc:call(‘server@Gentoo-PC’, test, call, [‘message from other node’]).

© 版权声明

相关文章