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

相关文章

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

SQL Server 查询数据库及数据文件大小的方法

《SQLServer查询数据库及数据文件大小的方法》文章介绍了查询数据库大小的SQL方法及存储过程实现,涵盖当前数据库、所有数据库的总大小及文件明细,本文结合实例代码给大家介绍的非常详细,感兴趣的... 目录1. 直接使用SQL1.1 查询当前数据库大小1.2 查询所有数据库的大小1.3 查询每个数据库的详

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

史上最全MybatisPlus从入门到精通

《史上最全MybatisPlus从入门到精通》MyBatis-Plus是MyBatis增强工具,简化开发并提升效率,支持自动映射表名/字段与实体类,提供条件构造器、多种查询方式(等值/范围/模糊/分页... 目录1.简介2.基础篇2.1.通用mapper接口操作2.2.通用service接口操作3.进阶篇3

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与