天天看點

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)

([email protected])1> c(distribution).

啟動本地節點,設定同樣的cookie

$ erl -name [email protected] -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)

([email protected])1> rpc:call('[email protected]',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},

    {pid,response}->

        response

檢視遠端的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

-r-------- 1 apple apple 21  1月  5 03:17 /home/apple/.erlang.cookie

啟動遠端節點,并載入子產品

apple@example:~/erlang$ erl -name gandalf

([email protected])1> c(remote_local).

{ok,remote_local}

啟動本地節點載入子產品,測試

apple@apple-system:~/erlang$ erl -name [email protected]

([email protected])1> c(remote_local).          

([email protected])2> pid=remote_local:start('[email protected]').

<9747.49.0>

([email protected])3> remote_local:echo(pid,hello).

([email protected])4> remote_local:echo(pid,hi).     

hi

([email protected])5>