Vinova tuyển lập trình viên Mobile & Web ở Hà Nội, lương $300-1000

Article: Lệnh RPC trong Erlang 750

saigon.myopenid.com 8
Updated over 2 years ago

Sử dụng lệnh rpc cho phép remote access đến 1 node khác.

Chúng ta thử làm ví dụ minh hoạ

Trên Server 1, tạo doan code sau

-module(kvs).
-export([start/0, store/2, lookup/1]).
start() -> register(kvs, spawn(fun() -> loop() end)).
store(Key, Value) -> rpc({store, Key, Value}).
lookup(Key) -> rpc({lookup, Key}).
rpc(Q) ->
kvs ! {self(), Q},
receive
{kvs, Reply} ->
Reply
end.
loop() ->
receive
{From, {store, Key, Value}} ->
put(Key, {ok, Value}),
From ! {kvs, true},
loop();
{From, {lookup, Key}} ->
From ! {kvs, get(Key)},
loop()
end.

Đoạn code trên làm nhiệm vụ rất đơn giản là store va lookup 1 giá trị

biên dịch và chạy

erl -sname test -setcookie abc
Erlang R13B01 (erts-5.7.2) [source] [64-bit] [rq:1] [async-threads:0] [kernel-poll:false]

Eshell V5.7.2 (abort with ^G)
(test@test1)1> kvs:start().
true
(test@test1)2>

chú ý tham số -setcookie, những node khác cũng phải được setcookie với giá trị giống nhau.

giờ ta start thêm 2 node trên 2 máy khác nhau

Trên Server2

test@test2:~/tmp/erlang$ erl -sname test -setcookie abc

Trên Server 3

test@test3:~/tmp/erlang$ erl -sname test -setcookie abc

Sử dụng module net_adm để set up connection giữa các Node

(test@test1)1> net_adm:ping(test@test2).
pong
(test1@test2)2>
(test@test2)1> net_adm:ping(test@test3).
pong
(test@test2)2>

Nếu thấy kết quả return là pong là ok.

Bây giờ từ Server 3, ta gọi đến module kvs trên Server 1

(test@test3)1> rpc:call(test@test1, kvs, store, [weather, cold]).
true
(test@test3)2> rpc:call(test1@test1, kvs, lookup, [weather]).
{ok,cold}

Bạn có thể thấy là chương trình đã làm việc chính xác.

Comments

You must login to be able to comment

Uploaded files

No file uploaded yet

You must login to be able to upload

Nhà tài trợ:

Mọi người đều tự do viết bài, sửa bài của người khác, và bình luận ở trang web này. Bạn muốn chủ động tạo bài mới để chia sẻ kinh nghiệm với mọi người? Xin click link ở dưới.

Create new content