下面的例子试用了erlang的分布式编程,从中可以看出像erlang这种基于消息的纯函数语言在分布式编程中的强大威力.
简单例子
在远程节点编写一个测试的模块
-module(distribution).
-export([a/0]).
a() ->
hello.
首先启动远程节点,并设置cookie,载入模块
$ erl -name remote -setcookie abc
Erlang R16B03 (erts-5.10.4) [source] [64-bit] [async-threads:10] [kernel-poll:false]
Eshell V5.10.4 (abort with ^G)
(remote@example.com)1> c(distribution).
启动本地节点,设置同样的cookie
$ erl -name client@192.168.1.156 -setcookie abc
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:2:2] [async-threads:10] [kernel-poll:false]
Eshell V7.0 (abort with ^G)
(client@192.168.1.156)1> rpc:call('remote@example.com',distribution,a,[]).
hello
要点
1.本地的长name,不能只写client,需要加上地址
复杂一点的例子
编写一个模块
-module(remote_local).
-export([start/1,echo/2]).
start(Node)-> spawn(Node,fun()->loop() end).
loop()->
receive
{From,Request}->
From!{self(),Request},
loop()
end.
echo(Pid,Request)->
Pid!{self(),Request},
receive
{Pid,Response}->
Response
end.
查看远端的cookie
$ cat ~/.erlang.cookie
FELWZVCNJEFSIMPPRBD
设置本地cookie和远端一样,并注意文件方法权限
apple@apple-System:~/erlang$ ll ~/.erlang.cookie
-r-------- 1 apple apple 20 1月 4 00:00 /home/apple/.erlang.cookie
apple@apple-System:~/erlang$ chmod 755 ~/.erlang.cookie
apple@apple-System:~/erlang$ echo FELWZVCNJEFSIMPPRBDI>~/.erlang.cookie
apple@apple-System:~/erlang$ chmod 400 ~/.erlang.cookie
apple@apple-System:~/erlang$ ll ~/.erlang.cookie
-r-------- 1 apple apple 21 1月 5 03:17 /home/apple/.erlang.cookie
启动远端节点,并载入模块
apple@example:~/erlang$ erl -name gandalf
Erlang R16B03 (erts-5.10.4) [source] [64-bit] [async-threads:10] [kernel-poll:false]
Eshell V5.10.4 (abort with ^G)
(gandalf@example.com)1> c(remote_local).
{ok,remote_local}
启动本地节点载入模块,测试
apple@apple-System:~/erlang$ erl -name bilbo@192.168.1.153
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:2:2] [async-threads:10] [kernel-poll:false]
Eshell V7.0 (abort with ^G)
(bilbo@192.168.1.153)1> c(remote_local).
{ok,remote_local}
(bilbo@192.168.1.153)2> Pid=remote_local:start('gandalf@example.com').
<9747.49.0>
(bilbo@192.168.1.153)3> remote_local:echo(Pid,hello).
hello
(bilbo@192.168.1.153)4> remote_local:echo(Pid,hi).
hi
(bilbo@192.168.1.153)5>