上一篇文章中說到, 注冊進程關聯的原子具有全局作用域, 這里的全局指的是當前 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']).