如果我有多个服务器实例,我如何将信息从一个传递到另一个,例如:
我有这个:
...
-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,
}}.
假设我有两台服务器,一台和两台。如何从服务器访问服务器2状态的一个信息?
答案 0 :(得分: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}