LoginSignup
1
1

More than 5 years have passed since last update.

Erlangのrpcを試してみる。

Last updated at Posted at 2016-11-11

これの続きです:http://qiita.com/syuhei/items/70fc971ce7ce40dee439

前回はHello Worldプロジェクトを作成しました。今回は分散プログラミングの基本となる、rpcモジュールを使ってみます。

myproject_app.erlにhello関数を追加します。exportに追加するのも忘れずに。

-export([start/2, stop/1, hello/1])
.
.
.

hello(Str) ->
    "Hello "++Str.

testフォルダを作成し、myproject_SUITE.erlを作成します。

このテストではrunner@{host名}からcluster_test@{host名}のjoin関数を呼び出しています。start_node関数が、新しくテスト用のノードを起動する関数です。

-module(myproject_SUITE).

-compile(export_all).

all() ->
    [cluster_test].

init_per_suite(_Config) ->
    {ok, Hostname} = inet:gethostname(),
    case net_kernel:start([list_to_atom("runner@"++Hostname), shortnames]) of
        {ok, _} -> ok;
        {error, {already_started, _}} -> ok
    end,
    _Config.

end_per_suite(_Config) ->
    application:stop(lager),
    _Config.

cluster_test(_Config) ->
    Node = start_node(cluster_test),
    R = rpc:call(Node, myproject_app, hello, ["World"]),
    ct:log("Result:~p, ", [R]),
    ct_slave:stop(Node).




start_node(Name) ->
    CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()),
    NodeConfig = [
            {monitor_master, true},
            {startup_functions, [
                    {code, set_path, [CodePath]}
                    ]}],
    case ct_slave:start(Name, NodeConfig) of
        {ok, Node} ->
            rpc:call(Node, application, ensure_all_started, [myproject_app]),
            Node;
        {error, already_started, Node} ->
            ct_slave:stop(Name),
            start_node(Name);
        {error, Reason, Node} ->
            io:format("error ~p~n", [Reason])
    end.


テストコマンドを打ちます。

$ ./rebar3 ct
===> Running Common Test suites...
%%% myproject_SUITE ==> cluster_test: OK
All 1 tests passed.

ちなみにログフォルダにテスト結果のHTMLもあります。./_build/test/logs/

runner@{host名}から"World"を送って、cluster_test@{host名}で"Hello "と連結すして、"Hello World"をrunner@{host名}に返しています。

スクリーンショット 2016-11-11 23.17.19.png

以上、簡単なrpcモジュールの使い方でした。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1