Ranch analysis and Learning (1)

Source: Internet
Author: User
Tags what magic

Ranch is a TCP processing program framework. The official explanation of ranch is a socket acceptor pool for TCP Protocols. It aims to provide a convenient, easy-to-use, efficient, and stable basic TCP processing program. I also used it as the basis to write a simple chat program. The underlying communication processing of cowboy is also ranch processing, and dozens of files are used as the basic HTTP server. Today, let's see what magic it has. There is not much nonsense. I will analyze it in the next few days and talk about my learning experience. If anything is wrong, please correct it.

Source code: https://github.com/extend/ranch

Example: https://github.com/extend/ranch/tree/master/examples

Download shell: git clone https://github.com/extend/ranch

First, let's take a look at a total of 13 files in the entire directory tree program. The entire program is organized in OTP mode.

  
├── ranch_acceptor.erl├── ranch_acceptors_sup.erl├── ranch_app.erl├── ranch.app.src├── ranch_conns_sup.erl├── ranch.erl├── ranch_listener_sup.erl├── ranch_protocol.erl├── ranch_server.erl├── ranch_ssl.erl├── ranch_sup.erl├── ranch_tcp.erl└── ranch_transport.erl
View code

1. First, let's take a look at ranch. App. SRC.

{application, ranch, [    {description, "Socket acceptor pool for TCP protocols."},    {vsn, "0.10.0"},    {modules, []},    {registered, [ranch_sup, ranch_server]},    {applications, [        kernel,        stdlib    ]},    {mod, {ranch_app, []}},    {env, [{profile,true}]}]}.

This file is mainly based on the Erlang OTP design principles, and I will not elaborate on the rest. Here we mainly look at the corresponding environment configuration options {ENV, [{profile, true}]}. This option is ranch's Efficiency Analysis for processes and is very useful in Optimizing and improving efficiency. Do not configure it in the production environment. Otherwise, the execution efficiency of the program will be affected. This file is required for application startup. After the application is published and packaged, use application: Start (ranch). To start application: Stop (ranch). to close the application.

2. Entry file for ranch_app.erl application startup

 1 -module(ranch_app). 2 -behaviour(application). 3  4 -export([start/2]). 5 -export([stop/1]). 6 -export([profile_output/0]). 7  8 start(_, _) -> 9     _ = consider_profiling(),10     ranch_sup:start_link().11 12 stop(_) ->13     ok.14 15 -spec profile_output() -> ok.16 profile_output() ->17     eprof:stop_profiling(),18     eprof:log("procs.profile"),19     eprof:analyze(procs),20     eprof:log("total.profile"),21     eprof:analyze(total).22 23 consider_profiling() ->24     case application:get_env(profile) of25         {ok, true} ->26             {ok, _Pid} = eprof:start(),27             eprof:start_profiling([self()]);28         _ ->29             not_profiling30     end.

This file is the specific implementation of the behavior mode application, and the entry of START (_, _) application startup. Stop (_) disables the external callback processing function of the application. This mainly allows us to save data before closing and clean up program data. . Here, we mainly pay attention to the two methods. The first method consider_profiling () reads the configuration file and determines whether to start the application performance analysis tool. The {ENV, [{profile, true}]} mentioned above indicates whether to enable the Performance Analysis configuration. The second method is profile_output (). print out the specific performance analysis.

Next let's take a look at the above performance analysis. Compile the Startup Program and call ranch_app: profile_output () in shell. The result is as follows:

1> application:start(ranch).ok2> toolbar:start().<0.42.0>3> ranch_app:profile_output().****** Process <0.37.0>    -- 31.48 % of profiled time *** FUNCTION                            CALLS      %  TIME  [uS / CALLS]--------                            -----    ---  ----  [----------]gen:where/1                             1   0.00     0  [      0.00]gen:timeout/1                           1   0.00     0  [      0.00]code:call/1                             1   0.00     0  [      0.00]proc_lib:start_link/5                   1   0.00     0  [      0.00]proc_lib:sync_wait/2                    1   0.00     0  [      0.00]proc_lib:get_ancestors/0                1   0.00     0  [      0.00]supervisor:start_link/3                 1   0.00     0  [      0.00]lists:member/2                          2   0.00     0  [      0.00]error_handler:undefined_function/3      1   1.96     1  [      1.00]gen:start/6                             1   1.96     1  [      1.00]

Called function, number of calls, percentage, time, and time required for one call. And so on. This is very helpful for improving program efficiency.

3. Next we will analyze and learn about ranch_sup.erl.

 1 -module(ranch_sup). 2 -behaviour(supervisor). 3  4 -export([start_link/0]). 5 -export([init/1]). 6  7 -spec start_link() -> {ok, pid()}. 8 start_link() -> 9     supervisor:start_link({local, ?MODULE}, ?MODULE, []).10 11 init([]) ->12     ranch_server = ets:new(ranch_server, [13         ordered_set, public, named_table]),14     Procs = [15         {ranch_server, {ranch_server, start_link, []},16             permanent, 5000, worker, [ranch_server]}17     ],18     {ok, {{one_for_one, 10, 10}, Procs}}.

What is the purpose of this file? If you think of ranch_app as the chairman of the board, the program ranch_sup is equivalent to the general manager of the company. It manages how the people below work and the intensity of work, and what if something goes wrong. All belong to it for management. It is the supervisor. Supervisor: start_link ({local ,? Module },? Module, []). Register a local process named ranch_sup. The registration process types are local, global, and via. The third is unclear about the specific functions, you only need to export three callback functions. Today we will talk about this for the time being, and the rest will continue tomorrow ..

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.