gen_server的一些心得

gen_server并不是我原来概念中的tcp_server或者udp_server的概念,只是一个纯粹的消息服务器,另外,附上它的一些回调函数的简单说明参考地址

http://hi.baidu.com/software_one/item/f5b07aeda3ac61215a2d64cd

● init/1 - 服务器的初始化;

● handle_call/3 - 处理对服务器的同步调用。调用服务器的客户端被阻塞,直到本函数返回。

● handle_cast/2 - 处理对服务器的异步调用。调用的执行过程中,客户端不被阻塞。

● handle_info/2 - 是起着“收容”作用的函数。服务器收到的信息,如果不是同步调用或异步调用,就交由这个函数处理。例如,如果你的服务器与其他进程相连接,那么,要求退出进程的信息,就是这个函数处理。
比如,别人拿到了gen_server的pid,给pid发消息,那么,消息会在这里被处理 ● terminate
/2 - 关闭服务器时,调用这个函数,做些善后处理。 ● code_change/3 - 服务器运行中更新时,调用这个函数。在后面的文章中,会涉及这个函数的大量细节,但你应该至少会按照基本要求使用它。

 

贴上一个例子

-module(new_storage).
-behaviour(gen_server).

-export([start/0,stop/1,add/3,find/2]).

-export([init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).

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

stop(Name)->
    gen_server:cast(Name, stop).

add(Name,Key,Value)->
    gen_server:call(Name,{add,Key,Value}).

find(Name,Key)->
    gen_server:call(Name,{find,Key}).

%% callbacks of gen_server
init([])->
    {ok,dict:new()}.

handle_call({add,Key,Value},_From,Dict)->
    Reply = dict:store(Key,Value,Dict),
    {reply,ok,Reply};
handle_call({find,Key},_From,Dict)->
    Reply = dict:find(Key,Dict),
    {reply,Reply,Dict}.

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

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

terminate(_Reason,_State)->
    io:format("terminate trapped~n"),
    ok.

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

示例:

33>{ok,Pid}=new_storage:start().
{ok,<0.97.0>}
34> new_storage:add(Pid,testKey,testValue).
ok
35> new_storage:find(Pid,testKey).         
{ok,testValue}
36> new_storage:stop(Pid).                 
terminate trapped
ok
37>

 

posted @ 2014-10-31 18:48  自由出土文物  阅读(699)  评论(0编辑  收藏  举报