首先,今天0點《暗黑破壞神3》就要正式開服了,但是我把晚上獻給了erlang,經過前幾天的努力,我已經看完了 Erlang OTP設計原則,在這里非常感謝,翻譯成中文的作者 ShiningRay,沒有你無私的奉獻,也就沒有我們這些菜鳥的幸福,廢話不多說,進入今天的正題,我在今后這一段時間,跟大家一起來分享 Cowboy 這個開源的 erlang http 服務器。
我們看下官方的簡介:
Cowboy is a small, fast and modular HTTP server written in Erlang.
Cowboy is also a socket acceptor pool, able to accept connections for any kind of TCP protocol.
源碼下載地址:https://github.com/extend/cowboy
例子:https://github.com/extend/cowboy_examples
首先是下載源碼:git clone https://github.com/extend/cowboy.git
好,我們開始分析 CowBoy這個項目,首先是
1. cowboy.app.src 這個文件,這個文件在編譯后為cowboy.app也就是應用資源文件,又稱為應用配置文件,Erlang不管是應用程序,還是一般的類庫,最后都是以應用程序的方式啟動,這個可以參看 Erlang OTP設計原則 中的 應用 ,內容如下:
{application, cowboy, [ {description, "Small, fast, modular HTTP server."}, {vsn, "0.5.0"}, {modules, []}, {registered, [cowboy_clock, cowboy_sup]}, {applications, [ kernel, stdlib ]}, {mod, {cowboy_app, []}}, {env, []} ]}.
資源文件中的每個字段我們在這邊就不詳細介紹了,推薦沒有看過 Erlang OTP 設計原則 的朋友去看下,它能幫助你了解 Erlang 整體上的結構,比如,應該程序下一般是監控進程,然后監控進程又負責監控子進程等等,當然,在這個文檔中,詳細描述了上面所有字段的含義。
配置文件中,鍵 mod 定義了回調模塊以及應用的啟動參數,在這個例子中相應是 cowboy_app 和 []。這表示應用啟動的時候會調用:
cowboy_app:start(normal, [])
而當應用被停止的時候會調用:
cowboy_app:stop([])
2. 既然上面提到 應用被啟動時,會調用 cowboy_app:start(normal, []),那么我們接下來看下下面這個文件:
cowboy_app.erl
-module(cowboy_app). -behaviour(application). -export([start/2, stop/1, profile_output/0]). %% API. -type application_start_type() :: normal | {takeover, node()} | {failover, node()}. %% API. -spec start(application_start_type(), any()) -> {ok, pid()}. start(_Type, _Args) -> consider_profiling(), cowboy_sup:start_link(). -spec stop(any()) -> ok. stop(_State) -> ok. -spec profile_output() -> ok. profile_output() -> eprof:stop_profiling(), eprof:log("procs.profile"), eprof:analyze(procs), eprof:log("total.profile"), eprof:analyze(total). %% Internal. -spec consider_profiling() -> profiling | not_profiling. consider_profiling() -> case application:get_env(profile) of {ok, true} -> {ok, _Pid} = eprof:start(), eprof:start_profiling([self()]); _ -> not_profiling end.
當應用程序啟動時,會調用這個方法 start(_Type, _Args) 這個方法有2個參數,_Args 這個參數是從 應用程序配置文件中 {mod, {cowboy_app, []}},在這里 [] 空列表,
_Type 這個參數的值一般為 normal;
我們看到在 start/2 方法中,有2行代碼,consider_profiling() 這個是 和 eprof相關的,今天先不詳細介紹,因為我也沒見過。。。抱歉,我大概百度了下,A Time Profiling Tool for Erlang 想研究的可以看下官方DOC http://www.erlang.org/doc/man/eprof.html 大概意思就是 erlang 代碼分析工具。
我們看 cowboy_sup:start_link() 這行的意思是啟動督程,就是監控進程,然后一般在其他子進程會在這棵監控進程樹下。
剩下一個方法就是 stop(_State), 用於停止應用程序使用。
下面介紹下啟動應用程序的方法:
application:start(cowboy).
停止應用程序的方法:
application:stop(cowboy).
今天就簡單介紹這2個文件。謝謝