Erlang Application #
一、Application概述 #
Application是Erlang/OTP中组织代码和资源的基本单元。
1.1 特点 #
- 代码组织单元
- 独立启动和停止
- 配置管理
- 依赖管理
二、应用结构 #
2.1 目录结构 #
text
my_app/
├── src/
│ ├── my_app.app.src
│ ├── my_app_app.erl
│ ├── my_app_sup.erl
│ └── my_server.erl
├── priv/
│ └── config/
├── ebin/
└── test/
2.2 app.src文件 #
erlang
{application, my_app,
[{description, "My Erlang Application"},
{vsn, "1.0.0"},
{registered, [my_server]},
{mod, {my_app_app, []}},
{applications,
[kernel,
stdlib,
crypto,
logger
]},
{env, [{port, 8080}]},
{modules, [my_app_app, my_app_sup, my_server]},
{licenses, ["MIT"]},
{links, ["https://github.com/user/my_app"]}
]}.
三、应用回调 #
3.1 application回调模块 #
erlang
-module(my_app_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, _Args) ->
io:format("Starting my_app~n"),
my_app_sup:start_link().
stop(_State) ->
io:format("Stopping my_app~n"),
ok.
3.2 start返回值 #
{ok, Pid}- 成功启动{ok, Pid, State}- 成功启动带状态{error, Reason}- 启动失败
四、应用配置 #
4.1 配置项 #
erlang
{env, [
{port, 8080},
{host, "localhost"},
{pool_size, 10},
{timeout, 5000}
]}.
4.2 读取配置 #
erlang
-module(config_reader).
-export([get_port/0, get_host/0, get_all/0]).
get_port() ->
application:get_env(my_app, port, 8080).
get_host() ->
application:get_env(my_app, host, "localhost").
get_all() ->
application:get_all_env(my_app).
4.3 运行时设置 #
erlang
set_port(Port) ->
application:set_env(my_app, port, Port).
五、应用管理 #
5.1 启动应用 #
erlang
application:start(my_app).
application:ensure_started(my_app).
5.2 停止应用 #
erlang
application:stop(my_app).
5.3 查看应用信息 #
erlang
application:info().
application:which_applications().
application:loaded_applications().
六、应用依赖 #
6.1 applications列表 #
erlang
{applications,
[kernel,
stdlib,
crypto,
logger,
inets,
ssl
]}.
6.2 included_applications #
erlang
{included_applications, [sub_app]}.
七、实际应用 #
7.1 Web应用 #
erlang
-module(web_app_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, _Args) ->
Port = application:get_env(web_app, port, 8080),
io:format("Starting web app on port ~p~n", [Port]),
web_app_sup:start_link().
stop(_State) ->
io:format("Stopping web app~n"),
ok.
7.2 数据库应用 #
erlang
-module(db_app_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, _Args) ->
Host = application:get_env(db_app, host, "localhost"),
Port = application:get_env(db_app, port, 5432),
io:format("Starting db app connecting to ~p:~p~n", [Host, Port]),
db_app_sup:start_link().
stop(_State) ->
io:format("Stopping db app~n"),
ok.
八、总结 #
本章学习了:
- Application概述
- 应用结构
- 应用回调
- 应用配置
- 应用管理
- 应用依赖
- 实际应用
准备好学习Release了吗?让我们进入下一章。
最后更新:2026-03-27