http://blog.chinaunix.net/uid-25876834-id-3308693.htmlcss
這裏介紹構建一個完整的Erlang/OTP應用的例子,最後還給出了一個在實際生成環境中,如何啓動應用的才能方便運維人員維護和部署的實例。例子摘自 《Manning.Erlang.and.OTP.in.Action》(國內目前已經有中文版發行)。html
關於該應用例子中,代碼和配置文件中的基本的概念的解釋我這裏就省略了。
一個完整而簡單的基於tcp的rpc 應用爲例,一個應用包括:
一、元數據文件 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, []}}
- ]}.
二、應用啓動模塊 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.
三、頂層監督模塊 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]
- }
- }.
四、服務器模塊 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.
五、啓動整個應用的開啓模塊 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.
六、啓動腳本 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程序
七、編譯代碼能夠經過:
erlc -o ebin src/*.erl
或者利用Emakefile
- { ["src/*"]
- , [
- {outdir, "./ebin"}]
- }.
配合 erl -make 來編譯這個應用。單元測試
八、啓動。由於咱們寫了啓動腳本和啓動模塊,因此不須要進入到erlang shell 裏面啓動這個應用,能夠直接經過執行 start_tr.sh 來啓動。
這裏給出一個完整又簡單的例子,但願能夠對剛接觸OTP知識的人有幫助。
- , [
- {outdir, "./ebin"}]
- }.
配合 erl -make 來編譯這個應用。
八、啓動。由於咱們寫了啓動腳本和啓動模塊,因此不須要進入到erlang shell 裏面啓動這個應用,能夠直接經過執行 start_tr.sh 來啓動。
這裏給出一個完整又簡單的例子,但願能夠對剛接觸OTP知識的人有幫助。