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数据库服务器IP地址的多种有效方法

《查询SQLServer数据库服务器IP地址的多种有效方法》作为数据库管理员或开发人员,了解如何查询SQLServer数据库服务器的IP地址是一项重要技能,本文将介绍几种简单而有效的方法,帮助你轻松... 目录使用T-SQL查询方法1:使用系统函数方法2:使用系统视图使用SQL Server Configu

SQL Server数据库迁移到MySQL的完整指南

《SQLServer数据库迁移到MySQL的完整指南》在企业应用开发中,数据库迁移是一个常见的需求,随着业务的发展,企业可能会从SQLServer转向MySQL,原因可能是成本、性能、跨平台兼容性等... 目录一、迁移前的准备工作1.1 确定迁移范围1.2 评估兼容性1.3 备份数据二、迁移工具的选择2.1

SQL Server使用SELECT INTO实现表备份的代码示例

《SQLServer使用SELECTINTO实现表备份的代码示例》在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误,在SQLServer中,可以使用SELECTINT... 在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误。在 SQL Server 中,可以使用 SE

Window Server创建2台服务器的故障转移群集的图文教程

《WindowServer创建2台服务器的故障转移群集的图文教程》本文主要介绍了在WindowsServer系统上创建一个包含两台成员服务器的故障转移群集,文中通过图文示例介绍的非常详细,对大家的... 目录一、 准备条件二、在ServerB安装故障转移群集三、在ServerC安装故障转移群集,操作与Ser

SQL Server数据库磁盘满了的解决办法

《SQLServer数据库磁盘满了的解决办法》系统再正常运行,我还在操作中,突然发现接口报错,后续所有接口都报错了,一查日志发现说是数据库磁盘满了,所以本文记录了SQLServer数据库磁盘满了的解... 目录问题解决方法删除数据库日志设置数据库日志大小问题今http://www.chinasem.cn天发

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题:

Java 创建图形用户界面(GUI)入门指南(Swing库 JFrame 类)概述

概述 基本概念 Java Swing 的架构 Java Swing 是一个为 Java 设计的 GUI 工具包,是 JAVA 基础类的一部分,基于 Java AWT 构建,提供了一系列轻量级、可定制的图形用户界面(GUI)组件。 与 AWT 相比,Swing 提供了许多比 AWT 更好的屏幕显示元素,更加灵活和可定制,具有更好的跨平台性能。 组件和容器 Java Swing 提供了许多

【IPV6从入门到起飞】5-1 IPV6+Home Assistant(搭建基本环境)

【IPV6从入门到起飞】5-1 IPV6+Home Assistant #搭建基本环境 1 背景2 docker下载 hass3 创建容器4 浏览器访问 hass5 手机APP远程访问hass6 更多玩法 1 背景 既然电脑可以IPV6入站,手机流量可以访问IPV6网络的服务,为什么不在电脑搭建Home Assistant(hass),来控制你的设备呢?@智能家居 @万物互联

poj 2104 and hdu 2665 划分树模板入门题

题意: 给一个数组n(1e5)个数,给一个范围(fr, to, k),求这个范围中第k大的数。 解析: 划分树入门。 bing神的模板。 坑爹的地方是把-l 看成了-1........ 一直re。 代码: poj 2104: #include <iostream>#include <cstdio>#include <cstdlib>#include <al