0

If I have several instances of server, how can I pass info from one to another, for example:

I have this:

...
-record(id,{name,hash}).
-record(state, {id ,m, succ, pred}).
start(Name, M) ->
      gen_server:start_link({local, Name}, ?MODULE, {new_ring, Name, M}, []).
join_ring(Name, Other) ->
      gen_server:start_link({local, Name}, ?MODULE, {join_ring, Name, Other}, []).

...
init({new_ring, Name, M}) ->
Me=#id{name=Name,hash=M}
{ok, #state{
   id    = Me,
   m     = M,
   succ  = Me,
   pred  = nil,
  }};
init({join_ring, Name, Other}) ->
Me=#id{name=Name,hash=M}
{ok, #state{
   id    = Me,
   m     = Other,
   succ  = Me,
   pred  = nil,
  }}.

Let say that I have two servers, one and two. How can I access from the server one info from the state of server two?

4

1 回答 1

1
-module(wy).
-compile(export_all).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-behaviour(gen_server).
-record(state, {id ,m, succ, pred}).

start(Name, M) ->
    gen_server:start_link({local, Name}, ?MODULE, [Name, M], []).

init([Name, M]) ->
    {ok, #state{id = Name, m = M}}.

handle_call({get_server_info}, _Frome, State) ->
    {reply, State, State};
handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


get_server_info(ServerName) ->
    gen_server:call(ServerName, {get_server_info}).

我认为您可以参考此代码示例。您可以为服务器命名,例如server1& server2。然后您使用gen_server:call/2将消息发送到您想要的服务器。

只需启动两个 gen_serber:

   4> wy:start(server1, server1).
    {ok,<0.50.0>}
    5> wy:start(server2, server2).
    {ok,<0.52.0>}

从服务器获取状态信息:

24> wy:get_server_info(server2).
{state,server2,server2,undefined,undefined}
25> wy:get_server_info(server1).
{state,server1,server1,undefined,undefined}
于 2014-09-16T02:39:28.433 回答