erlang远程调用示例

下面的例子试用了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>












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值