%%%------------------------------------------------------------------- %% @doc iot public API %% @end %%%------------------------------------------------------------------- -module(iot_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> io:setopts([{encoding, unicode}]), %% 加速内存的回收 erlang:system_flag(fullsweep_after, 16), %% 启动mnesia数据库 start_mnesia(), %% 启动http服务 start_http_server(), %% 启动tcp服务 start_tcp_server(), iot_sup:start_link(). stop(_State) -> ok. %% internal functions %% 启动内存数据库 start_mnesia() -> ok = ensure_mnesia_schema(), %% 启动数据库 ok = mnesia:start(), Tables = mnesia:system_info(tables), lager:debug("[iot_app] tables: ~p", [Tables]), %% 创建数据库表 ok. start_http_server() -> {ok, Props} = application:get_env(iot, http_server), Acceptors = proplists:get_value(acceptors, Props, 50), MaxConnections = proplists:get_value(max_connections, Props, 10240), Backlog = proplists:get_value(backlog, Props, 1024), Port = proplists:get_value(port, Props), Dispatcher = cowboy_router:compile([ {'_', [ {"/host/[...]", http_protocol, [host_handler]}, {"/container/[...]", http_protocol, [container_handler]}, {"/device/[...]", http_protocol, [device_handler]}, {"/event_stream", event_stream_handler, []} ]} ]), TransOpts = #{ max_connections => MaxConnections, num_acceptors => Acceptors, shutdown => brutal_kill, socket_opts => [ {backlog, Backlog}, {port, Port} ] }, {ok, Pid} = cowboy:start_clear(http_listener, TransOpts, #{env => #{dispatch => Dispatcher}}), lager:debug("[http_server] the http server start at: ~p, pid is: ~p", [Port, Pid]). %% 启动tcp服务 start_tcp_server() -> {ok, Props} = application:get_env(iot, tcp_server), Acceptors = proplists:get_value(acceptors, Props, 50), MaxConnections = proplists:get_value(max_connections, Props, 10240), Backlog = proplists:get_value(backlog, Props, 1024), Port = proplists:get_value(port, Props), TransOpts = #{ max_connections => MaxConnections, num_acceptors => Acceptors, shutdown => brutal_kill, socket_opts => [ {nodelay, false}, {backlog, Backlog}, {port, Port} ] }, {ok, _} = ranch:start_listener(tcp_server, ranch_tcp, TransOpts, tcp_channel, []), lager:debug("[iot_app] the tcp server start at: ~p", [Port]). -spec ensure_mnesia_schema() -> any(). ensure_mnesia_schema() -> case mnesia:system_info(use_dir) of true -> ok; false -> mnesia:stop(), case mnesia:create_schema([node()]) of ok -> ok; {error, {_, {already_exists, _}}} -> ok; Error -> lager:debug("[iot_app] create mnesia schema failed with error: ~p", [Error]), throw({init_schema, Error}) end end.