Erlang gen_server communication

天涯浪子 提交于 2019-12-11 23:14:57

问题


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?


回答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}).

I think you can refer this code sampe. You can give the server a name, for example server1 & server2. Then you use gen_server:call/2 to send the message to the server you wanted.

just start two gen_serber:

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

To get the state info from the server:

24> wy:get_server_info(server2).
{state,server2,server2,undefined,undefined}
25> wy:get_server_info(server1).
{state,server1,server1,undefined,undefined}


来源:https://stackoverflow.com/questions/25859241/erlang-gen-server-communication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!