一.why otp
otp设计原理是用来使进程、模块和目录中的erlang代码结构化的一系列原理。其最基本的思想就是监督树,然后是行为模式,应用和版本发布。
二.gen_server
gen_server是行为模式,上一篇将了服务器的演化,其实就是gen_server的基础,也就是一个大的运行框架。借由这个框架,我们把业务和功能更好的划分开,使功能代码与业务彻底解耦,业务更新不会设计功能的修改,功能的修改也不会导致业务重写。
gen_server的使用很简单,因为gen_server已经具备了基本的功能代码,只要自己把几个必备的业务接口填充上,就可以启动gen_server了。
start_link() ->
gen_server:start_link({local, ch3}, ch3, [], []) => {ok, Pid}
start_link会生成并连接到一个新gen_server进程。第一个参数指明了gen_server需要用什么名字注册到什么地方。第二个参数是回调模块名字,这个名字一般与注册名用同一个,第三个参数是传给init方法的参数列表,第四个参数是gen_server的参数列表。
init(_Args) ->
{ok, channels()}.
初始化方法,start_link会等待init完成。
handle_call(alloc, _From, Chs) ->
{Ch, Chs2} = alloc(Chs),
{reply, Ch, Chs2}.
handle_call同步请求回调。
handle_cast({free, Ch}, Chs) ->
Chs2 = free(Ch, Chs),
{noreply, Chs2}.
handle_cast异步请求回调。
terminate(shutdown, State) ->
..code for cleaning up here..
ok.
退出清理
handle_info({'EXIT', Pid, Reason}, State) ->
..code to handle exits here..
{noreply, State1}.
带外消息处理
三.gen_fsm:个人觉得把状态理清,然后把{next_state,,,}这个填好就可以了
四.gen_event
五.supervisor
one_for_one:进程有问题时,重启该进程
one_for_all:一个进程有问题,全部进程重启
rest_for_one:Then the terminated child process and the rest of the child processes are restarted.