---
title: "gen_server入门 "
author: "wgcode"
date: "2011-08-03T14:55:02Z"
tags: []
categories: ["编程语言"]
slug: "gen-server"
draft: false
lastmod: "2011-08-03T14:55:02Z"
id: 1139108
url: "https://tts.iteye.com/blog/1139108"
---

gen\_server入门 

1）什么是gen\_server？   
gen\_server是OTP（Open Telecom Platform）的一个组件，OTP是Erlang的应用程序框架，gen\_server定义了自己的一套规范，用来写Erlang服务器程序   
gen\_server manual: [http://www.erlang.org/doc/man/gen\_server.html](http://www.erlang.org/doc/man/gen_server.html) 

2）使用gen\_server程序的三个步骤：   
1，为callback module起个名字   
2，写接口function   
3，在callback module里写6个必需的callback function 

3）behaviour   
关键字-behaviour供编译器使用，如果我们的gen\_server程序没有定义合适的callback function则编译时会出错误和警告 

4）gen\_server模板 

```
%%%-------------------------------------------------------------------  
%%% File    : gen_server_template.full  
%%% Author  : my name <yourname@localhost.localdomain>  
%%% Description :   
%%%  
%%% Created :  2 Mar 2007 by my name <yourname@localhost.localdomain>  
%%%-------------------------------------------------------------------  
-module().  
  
-behaviour(gen_server).  
  
%% API  
-export([start_link/0]).  
  
%% gen_server callbacks  
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,  
     terminate/2, code_change/3]).  
  
-record(state, {}).  
  
%%====================================================================  
%% API  
%%====================================================================  
%%--------------------------------------------------------------------  
%% Function: start_link() -> {ok,Pid} | ignore | {error,Error}  
%% Description: Starts the server  
%%--------------------------------------------------------------------  
start_link() ->  
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).  
  
%%====================================================================  
%% gen_server callbacks  
%%====================================================================  
  
%%--------------------------------------------------------------------  
%% Function: init(Args) -> {ok, State} |  
%%                         {ok, State, Timeout} |  
%%                         ignore               |  
%%                         {stop, Reason}  
%% Description: Initiates the server  
%%--------------------------------------------------------------------  
init([]) ->  
    {ok, #state{}}.  
  
%%--------------------------------------------------------------------  
%% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} |  
%%                                      {reply, Reply, State, Timeout} |  
%%                                      {noreply, State} |  
%%                                      {noreply, State, Timeout} |  
%%                                      {stop, Reason, Reply, State} |  
%%                                      {stop, Reason, State}  
%% Description: Handling call messages  
%%--------------------------------------------------------------------  
handle_call(_Request, _From, State) ->  
    Reply = ok,  
    {reply, Reply, State}.  
  
%%--------------------------------------------------------------------  
%% Function: handle_cast(Msg, State) -> {noreply, State} |  
%%                                      {noreply, State, Timeout} |  
%%                                      {stop, Reason, State}  
%% Description: Handling cast messages  
%%--------------------------------------------------------------------  
handle_cast(_Msg, State) ->  
    {noreply, State}.  
  
%%--------------------------------------------------------------------  
%% Function: handle_info(Info, State) -> {noreply, State} |  
%%                                       {noreply, State, Timeout} |  
%%                                       {stop, Reason, State}  
%% Description: Handling all non call/cast messages  
%%--------------------------------------------------------------------  
handle_info(_Info, State) ->  
    {noreply, State}.  
  
%%--------------------------------------------------------------------  
%% Function: terminate(Reason, State) -> void()  
%% Description: This function is called by a gen_server when it is about to  
%% terminate. It should be the opposite of Module:init/1 and do any necessary  
%% cleaning up. When it returns, the gen_server terminates with Reason.  
%% The return value is ignored.  
%%--------------------------------------------------------------------  
terminate(_Reason, _State) ->  
    ok.  
  
%%--------------------------------------------------------------------  
%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}  
%% Description: Convert process state when code is changed  
%%--------------------------------------------------------------------  
code_change(_OldVsn, State, _Extra) ->  
    {ok, State}.  
  
%%--------------------------------------------------------------------  
%%% Internal functions  
%%--------------------------------------------------------------------
```

 gen\_server:start\_link(Name, Mod, InitArgs, Opts)创建一个名为Name的server，callback moudle为Mod 

Mod:init(InitArgs)启动server   
client端程序调用gen\_server:call(Name, Request)来调用server，server处理逻辑为handle\_call/3   
gen\_server:cast(Name, Name)调用callback handle\_cast(\_Msg, State)以改变server状态   
handle\_info(\_Info, State)用来处理发给server的自发消息   
terminate(\_Reason, State)是server关闭时的callback   
code\_change是server热部署或代码升级时做callback修改进程状态 

5）my\_bank例子 

```
%% ---  
%%  Excerpted from "Programming Erlang",  
%%  published by The Pragmatic Bookshelf.  
%%  Copyrights apply to this code. It may not be used to create training material,   
%%  courses, books, articles, and the like. Contact us if you are in doubt.  
%%  We make no guarantees that this code is fit for any purpose.   
%%  Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information.  
%%---  
-module(my_bank).  
  
-behaviour(gen_server).  
-export([start/0]).  
%% gen_server callbacks  
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,  
     terminate/2, code_change/3]).  
-compile(export_all).  
  
  
start() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).  
stop()  -> gen_server:call(?MODULE, stop).  
  
new_account(Who)      -> gen_server:call(?MODULE, {new, Who}).  
deposit(Who, Amount)  -> gen_server:call(?MODULE, {add, Who, Amount}).  
withdraw(Who, Amount) -> gen_server:call(?MODULE, {remove, Who, Amount}).  
  
  
  
init([]) -> {ok, ets:new(?MODULE,[])}.  
  
handle_call({new,Who}, _From, Tab) ->  
    Reply = case ets:lookup(Tab, Who) of  
        []  -> ets:insert(Tab, {Who,0}),   
               {welcome, Who};  
        [_] -> {Who, you_already_are_a_customer}  
        end,  
    {reply, Reply, Tab};  
handle_call({add,Who,X}, _From, Tab) ->  
    Reply = case ets:lookup(Tab, Who) of  
        []  -> not_a_customer;  
        [{Who,Balance}] ->  
            NewBalance = Balance + X,  
            ets:insert(Tab, {Who, NewBalance}),  
            {thanks, Who, your_balance_is,  NewBalance}   
        end,  
    {reply, Reply, Tab};  
handle_call({remove,Who, X}, _From, Tab) ->  
    Reply = case ets:lookup(Tab, Who) of  
        []  -> not_a_customer;  
        [{Who,Balance}] when X =< Balance ->  
            NewBalance = Balance - X,  
            ets:insert(Tab, {Who, NewBalance}),  
            {thanks, Who, your_balance_is,  NewBalance};      
        [{Who,Balance}] ->  
            {sorry,Who,you_only_have,Balance,in_the_bank}  
        end,  
    {reply, Reply, Tab};  
handle_call(stop, _From, Tab) ->  
    {stop, normal, stopped, Tab}.  
  
handle_cast(_Msg, State) -> {noreply, State}.  
handle_info(_Info, State) -> {noreply, State}.  
terminate(_Reason, _State) -> ok.  
code_change(_OldVsn, State, Extra) -> {ok, State}.
```

 6）编译运行my\_bank: 

```
Eshell > c(my_bank).  
Eshell > my_bank:start().  
Eshell > my_bank:new_account("hideto").  
Eshell > my_bank:deposit("hideto", 100).  
Eshell > my_bank:deposit("hideto", 200).  
Eshell > my_bank:withdraw("hideto", 10).  
Eshell > my_bank:withdraw("hideto", 10000).
```