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配置管理器打不开的问题,尝试在开始菜单栏搜SQLServerManager无果,于是将自己找到的方法总结分享给大家,对SQ... 目录方法一:桌面图标进入方法二:运行窗口进入方法三:查找文件路径方法四:检查 SQL Server 安

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)的解决方法

《mysql出现ERROR2003(HY000):Can‘tconnecttoMySQLserveron‘localhost‘(10061)的解决方法》本文主要介绍了mysql出现... 目录前言:第一步:第二步:第三步:总结:前言:当你想通过命令窗口想打开mysql时候发现提http://www.cpp

SQL Server清除日志文件ERRORLOG和删除tempdb.mdf

《SQLServer清除日志文件ERRORLOG和删除tempdb.mdf》数据库再使用一段时间后,日志文件会增大,特别是在磁盘容量不足的情况下,更是需要缩减,以下为缩减方法:如果可以停止SQLSe... 目录缩减 ERRORLOG 文件(停止服务后)停止 SQL Server 服务:找到错误日志文件:删除

Windows Server服务器上配置FileZilla后,FTP连接不上?

《WindowsServer服务器上配置FileZilla后,FTP连接不上?》WindowsServer服务器上配置FileZilla后,FTP连接错误和操作超时的问题,应该如何解决?首先,通过... 目录在Windohttp://www.chinasem.cnws防火墙开启的情况下,遇到的错误如下:无法与

一文详解SQL Server如何跟踪自动统计信息更新

《一文详解SQLServer如何跟踪自动统计信息更新》SQLServer数据库中,我们都清楚统计信息对于优化器来说非常重要,所以本文就来和大家简单聊一聊SQLServer如何跟踪自动统计信息更新吧... SQL Server数据库中,我们都清楚统计信息对于优化器来说非常重要。一般情况下,我们会开启"自动更新

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

JAVA虚拟机中 -D, -X, -XX ,-server参数使用

《JAVA虚拟机中-D,-X,-XX,-server参数使用》本文主要介绍了JAVA虚拟机中-D,-X,-XX,-server参数使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录一、-D参数二、-X参数三、-XX参数总结:在Java开发过程中,对Java虚拟机(JVM)的启动参数进

Windows server服务器使用blat命令行发送邮件

《Windowsserver服务器使用blat命令行发送邮件》在linux平台的命令行下可以使用mail命令来发送邮件,windows平台没有内置的命令,但可以使用开源的blat,其官方主页为ht... 目录下载blatBAT命令行示例备注总结在linux平台的命令行下可以使用mail命令来发送邮件,Win