这里介绍构建一个完整的Erlang/OTP应用的例子,最后还给出了一个在实际生成环境中,如何启动应用的才能方便运维人员维护和部署的实例。例子摘自 《Manning.Erlang.and.OTP.in.Action》(国内目前已经有中文版发行)。
关于该应用例子中,代码和配置文件中的基本的概念的解释我这里就省略了。
一个完整而简单的基于tcp的rpc 应用为例,一个应用包括:
1、元数据文件 tcp_rpc.app
- {application,tcp_rpc,
- [{description,"RPC Server for Erlang and OTP in action"},
- {vsn, "0.1.0"},
- {modules,[tr_app,
- tr_sup,
- tr_server]},
- {registered, [tr_sup]},
- {applications, [kernel, stdlib]},
- {mod, {tr_app, []}}
- ]}.
2、应用启动模块 tr_app.erl
- -module(tr_app).
- -behaviour(application).
- %% --------------------------------------------------------------------
- %% Include files
- %% --------------------------------------------------------------------
- %% --------------------------------------------------------------------
- %% Behavioural exports
- %% --------------------------------------------------------------------
- -export([
- start/2,
- stop/1
- ]).
- %% --------------------------------------------------------------------
- %% Internal exports
- %% --------------------------------------------------------------------
- %% -export([]).
- %% ====================================================================!
- %% External functions
- %% ====================================================================!
- %% --------------------------------------------------------------------
- %% Func: start/2
- %% Returns: {ok, Pid} |
- %% {ok, Pid, State} |
- %% {error, Reason}
- %% --------------------------------------------------------------------
- start(_Type, _StartArgs) ->
- case tr_sup:start_link() of
- {ok, Pid} ->
- {ok, Pid};
- Error ->
- {error,Error}
- end.
- %% --------------------------------------------------------------------
- %% Func: stop/1
- %% Returns: any
- %% --------------------------------------------------------------------
- stop(_State) ->
- ok.
3、顶层监督模块 tr_sup.erl
- -module(tr_sup).
- -behaviour(supervisor).
- -export([start_link/0]).
- -export([
- init/1
- ]).
- -define(SERVER, ?MODULE).
- start_link() ->
- supervisor:start_link({local, ?SERVER}, ?MODULE, []).
- init([]) ->
- Server = {tr_server,
- {tr_server,start_link,[]},
- permanent, 2000, worker, [tr_server]},
- {ok,{
- {one_for_one,0,1},
- [Server]
- }
- }.
4、服务器模块 tr_server.erl
- %%%-------------------------------------------------------------------
- %%% @author <龙二>
- %%% @copyright (C) 2012,
- %%% @doc RPC over TCP server. This module defines a server process that
- %%% listens for incoming TCP connections and allows the user to
- %%% execute RPC commands via that TCP stream.
- %%% @end
- %%% Created : 2 Jul 2012 by <emacs>
- %%%-------------------------------------------------------------------
- -module(tr_server).
- -include_lib("eunit/include/eunit.hrl"). %% Eunit单元测试
- -behaviour(gen_server).
- %% API
- -export([
- start_link/1,
- start_link/0,
- get_count/0,
- stop/0
- ]).
- %% gen_server callbacks
- -export([init/1,handle_call/3,handle_cast/2,handle_info/2,
- terminate/2,code_change/3]).
- -define(SERVER,?MODULE).
- -define(DEFAULT_PORT,1055).
- -record(state,{port,lsock,request_count = 0}).
- %%%===================================================
- %%% API
- %%%===================================================
- %%----------------------------------------------------
- %% @doc Starts the server.
- %%
- %% @spec start_link(Port::integer()) -> {ok,Pid}
- %% where
- %% Pid = pid()
- %% @end
- %%----------------------------------------------------
- start_link(Port) ->
- gen_server:start_link({local,?SERVER},?MODULE,[Port],[]).
- %% @spec start_link() -> {ok,Pid}
- %% @doc Calls 'start_link(Port)' using the default port
- start_link() ->
- start_link(?DEFAULT_PORT).
- %%----------------------------------------------------
- %% @doc Fetches the number of requests made to this server
- %% @spec get_count() -> {ok,Count}
- %% where
- %% Count = integer()
- %% @end
- %%----------------------------------------------------
- get_count() ->
- gen_server:call(?SERVER,get_count).
- %%----------------------------------------------------
- %% @doc Stops the server
- %% @spec stop() -> ok
- %% @end
- %%----------------------------------------------------
- stop() ->
- gen_server:cast(?SERVER,stop).
- %%%===================================================
- %%% gen_server callbacks
- %%%===================================================
- init([Port]) ->
- {ok,LSock} = gen_tcp:listen(Port,[{active,true}]),
- %% 0 is timeout value
- %% a atom msg 'timeout' will be generate
- %% handle_info/2 will handle this msg immediately when init/1 finished
- {ok,#state{port = Port,lsock = LSock},0}.
- handle_call(get_count,_From,State) ->
- {reply,{ok,State#state.request_count},State}.
- handle_cast(stop,State) ->
- {stop,normal,State}.
- %% handle_info/2: handle tcp,port,timeout msg
- handle_info({tcp,Socket,RawData},State) ->
- do_rpc(Socket,RawData),
- RequestCount = State#state.request_count,
- {noreply,State#state{request_count = RequestCount + 1}};
- handle_info(timeout,#state{lsock = LSock} = State) ->
- {ok,_Sock} = gen_tcp:accept(LSock),
- {noreply,State}.
- terminate(_Reason,_State) ->
- ok.
- code_change(_OldVsn,State,_Extra) ->
- {ok,State}.
- %%%===================================================
- %%% Internal functions
- %%%===================================================
- do_rpc(Socket,RawData) ->
- try
- {M,F,A} = split_out_mfa(RawData),
- Request = apply(M,F,A),
- gen_tcp:send(Socket,io_lib:fwrite("~p~n",[Request]))
- catch
- _Class:Err ->
- gen_tcp:send(Socket,io_lib:fwrite("~p~n",[Err]))
- end.
- split_out_mfa(RawData) ->
- MFA = re:replace(RawData,"\r\n$","",[{return,list}]),
- {match,[M,F,A]} =
- re:run(MFA,
- "(.*):(.*)\s*\\((.*)\s*\\)\s*.\s*$",
- [{capture,[1,2,3],list},ungreedy]),
- {list_to_atom(M),list_to_atom(F),args_to_terms(A)}.
- args_to_terms(RawArgs) ->
- {ok,Toks,_Line} = erl_scan:string("[" ++ RawArgs ++ "]. ",1),
- {ok,Args} = erl_parse:parse_term(Toks),
- Args.
5、启动整个应用的开启模块 tr.erl
- -module(tr).
- -export([start/0]).
- %%
- %% API Functions
- %%
- %% 启动应用
- start() ->
- case application:start(tcp_rpc) of
- ok ->
- ok;
- Msg ->
- {failur, Msg}
- end.
- %% 关闭应用
- stop() ->
- case application:stop(tcp_rpc) of
- ok ->
- ok;
- Msg ->
- {failure, Msg}
- end.
6、启动脚本 start_tr.sh (windows下为start_tr.bat)
- erl -pa ebin -name tr@127.0.0.1 -setcookie tr -s tr start
- chmod +x start_tr.sh
- windows下的话,需要将erl这个程序加入到环境变量,否则就要使用绝对路径来应用erl程序
7、编译代码可以通过:
erlc -o ebin src/*.erl
或者利用Emakefile
- { ["src/*"]
- , [
- {outdir, "./ebin"}]
- }.
配合 erl -make 来编译这个应用。
8、启动。因为我们写了启动脚本和启动模块,所以不需要进入到erlang shell 里面启动这个应用,可以直接通过执行 start_tr.sh 来启动。
这里给出一个完整又简单的例子,希望可以对刚接触OTP知识的人有帮助。
阅读(4920) | 评论(0) | 转发(0) |