gen_server入门

2024-05-04 18:18
文章标签 入门 server gen

本文主要是介绍gen_server入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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 

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).
 

这篇关于gen_server入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/959815

相关文章

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Redis 配置文件使用建议redis.conf 从入门到实战

《Redis配置文件使用建议redis.conf从入门到实战》Redis配置方式包括配置文件、命令行参数、运行时CONFIG命令,支持动态修改参数及持久化,常用项涉及端口、绑定、内存策略等,版本8... 目录一、Redis.conf 是什么?二、命令行方式传参(适用于测试)三、运行时动态修改配置(不重启服务

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存