1. 程式人生 > >Erlang學習記錄:app demo

Erlang學習記錄:app demo

avi art ++ .config tco 結構 conf std lose

目錄結構

│  Emakefile
│  make.bat
│  start.bat
├─config
│      config.config
│      server.app
├─ebin
│      wulin_app.beam
│      wulin_sup.beam
│      util.beam
│      demo.beam
├─logs
│      debug.log
└─src
       wulin_app.erl
       wulin_sup.erl
       util.erl
       demo.erl

config 配置目錄

ebin 編譯輸出目錄

logs 日誌輸出目錄

src 源代碼目錄

Emakefile(編譯配置)

{["src/*"],[{outdir, "ebin"}]}.

src/* 表示編譯src目錄下所有的源代碼文件

outdir 指定編譯後的beam文件輸出目錄

make.bat(編譯命令)

erl -make all

start.bat(啟動app)

cd config
erl -name [email protected] -setcookie mywulin -boot start_sasl -noshell -config config -pa ../ebin/ -s wulin_app start

-noshell 禁止輸入

-config xxx 加載文件名為xxx.config的配置

-pa 指定目錄

-s xxx yyy 啟動xxx模塊的yyy函數

config.config(env變量)

[
    {
        sasl,
        [
            {sasl_error_logger, false},
            {errlog_type, error},
            {error_logger_mf_dir, "../logs"},
            {error_logger_mf_maxbytes, 1048760},
            {error_logger_mf_maxfiles
, 10} ] },{ ab, [] } ].

可以在程序內使用application:get_env/2獲取這裏定義的變量

示例:application:get_env(sasl, error_logger_mf_dir). 返回{ok,"../logs"}

server.app

{
   application, server % 對應文件名
   , [{description,  "Server"}
      , {vsn, ‘1.0a‘}
      , {modules, []}
      , {registered, []}
      , {applications, [kernel, stdlib, sasl]} % 依賴庫
      , {env, [{author, "demo"}]}
      , {mod, {wulin_app, [12321]}} % 依賴模塊,主模塊
      , {start_phases, []}]
}.

server(app名)必須和server.app(文件名)一致

wulin_app.erl

-module(wulin_app).
-behaviour(application). 
-export([start/2,start/0, stop/1]). 

start() ->
 application:start(server).

start(_Type, [A]) ->  
    util:debug("Server Starting.... ~p ~n", [A]),  
    util:debug("Server Starting.... ~n", []),  
    {ok, Pid} = wulin_sup:start_link(),  
    util:debug("Server Started in ~p ~n", [Pid]),      
    {ok, Pid}.  
    
stop(_State) ->  
    io:format("Server Stoped..... ~n"). 

application:start(server)中的server對應server.app中的server

wulin_sup.erl

-module(wulin_sup).
-behaviour(supervisor).

-export([start_link/0,init/1]).

start_link() ->  
    supervisor:start_link({local,?MODULE}, ?MODULE, []).

init([]) ->   
    {ok, {{one_for_one, 3, 10},[
        {demo, {demo, start, []}, permanent, 10000, worker, []}
    ]}}.  

demo.erl

-module(demo).

-export([start/0]).

start() ->  
    util:debug("xxxxx ~n", []),
    {‘ok‘, self()}.

util.erl

-module(util).
-export([debug/2]). 

debug(F, Args) ->
    {ok, LogPath} = application:get_env(sasl, error_logger_mf_dir),
    File = LogPath ++ "/debug.txt",
    {ok, Steam} = file:open(File, [write, append]),
    io:format(Steam, F, Args),
    file:close(Steam).

debug.log

Server Starting.... 12321 
Server Starting.... 
xxxxx 
Server Started in <0.49.0> 

流程

start.bat -> wulin_app:start/0 -> server.app ->

wulin_app:start/2 -> wulin_sup:start_link/0 -> demo:start/0

Erlang學習記錄:app demo