Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Этот безумный, безумный

        Erlang
Структуры данных

● lists (proplists)
● sets
● dict
● gb_trees
● queue
● orddicts
● ordsets
● digraph
● array
OTP

● gen_server
● supervisor
● gen_fsm
● gen_event
gen_server
-module(mygenserv).
%-behaviour(gen_server).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2]).
-export([sync_incr/0, async_incr/0, get_value/0]).

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

sync_incr() ->
  gen_server:call(?MODULE, incr).

async_incr() ->
  gen_server:cast(?MODULE, incr).

get_value() ->
  gen_server:call(?MODULE, get_value).

init(I) ->
   State = I,
   {ok, State}.

handle_call(get_value, _From, State) ->
  {reply, State, State}.
handle_call(incr, _From, State) ->
  {reply, State, State + 1}.

handle_cast(incr, State) ->
  {noreply, State + 1}.
supervisor
-module(myapp_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).

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

init(_) ->
   MyGenServSpec = {
                    mygenserv,
                    {mygenserv, start_link, []},
                    permanent,
                    5000,
                    worker,
                    [mygenserv]
                 },
   ChildSpecs = [MyGenServSpec]
   {ok, {one_for_one, 100, 1}, ChildSpecs}.
Хранилища и БД из коробки

● ETS – in-memory хранилище


● DETS – дисковое хранилище


● Mnesia – распределенная база данных на базе ETS&DETS
rebar

# git clone https://github.com/basho/rebar

# cd rebar

# make

# cp rebar ~/src/myproject

# cd ~/src/myproject
rebar.config

{deps,
   [
     {mochiweb, "v1.1",
        {git, "https://github.com/mochi/mochiweb", {branch, "master"}}
   ]
}.
{erl_opts, [debug_info]}.
# ./rebar create-app appid=myapp
# ./rebar get-deps
# ./rebar compile

# erl -pa ebin

1> application:start(myapp).
# rebar -c

clean                        Clean
compile                       Compile sources

create     template= [var=foo,...] Create skel based on template and vars
create-app [appid=myapp]            Create simple app skel
create-node [nodeid=mynode]           Create simple node skel
list-templates              List available templates

doc                          Generate Erlang program documentation

check-deps                       Display to be fetched dependencies
get-deps                       Fetch dependencies
update-deps                      Update fetched dependencies
delete-deps                     Delete fetched dependencies
list-deps                     List dependencies

generate     [dump_spec=0/1]           Build release with reltool

generate-upgrade previous_release=path Build an upgrade package

generate-appups previous_release=path Generate appup files

eunit       [suite=foo]         Run eunit [test/foo_tests.erl] tests
ct        [suite=] [case=]      Run common_test suites in ./test

xref                         Run cross reference analysis

help                         Show the program options
version                       Show version information
Mochiweb
      git clone https://github.com/mochi/mochiweb


● Легкий высокопроизводительный HTTP-сервер

● mochijson, mochijson2 – Erlang terms в JSON и обратно

● mochiglobal – эмуляция глобальных переменных

● reloader

● Мелкие полезные утилиты (mochinum, mochilists, etc)

● Есть форк с поддержкой websockets
mochiweb_http

mochiweb_http:start([
    {port, 8080},
    {ip, "0.0.0.0"},
    {loop, fun handle_request/1}
]).

handle_request(Req) ->
  Method = Req:get(method),
  Path = Req:get(path),
  GETParams = Req:parse_qs(),
  POSTParams = Req:parse_post(),
  Req:ok({"text/html", "ok"}).
mochijson2

Props = [
   {age, 10},
   {name, <<"Snoopy">>},
   {talents, [<<"jumping">>, <<"barking">>, <<"sleeping">>]}
],
Obj = {struct, Props},

JSON = mochijson2:encode(Obj),

Req:ok({"application/json", JSON}).

...

1> mochijson2:decode(<<"{"a": "test"}">>).
{struct, [{<<"a">>,<<"test">>}] }
reloader

# erl -pa ebin -s reloader

                             # vi src/myapp.erl
                             ...
                             # ./rebar compile

Reloading myapp ... ok.
Другие веб-сервера

● YAWS

● misultin (очень похож на mochiweb, но полегче и попроще)

● cowboy (похож на mochiweb и misultin, но использует не
  parametrized modules, а callbacks)
Riak
          git clone https://github.com/basho/riak

● riak_core – фреймворк для создания распределенных систем

● riak_error – ограничение размера error reports

● lager – фрймворк для логирования

● basho_bench – утилита для измерения производительности

● rebar
lager

lager:error("oh no!")
lager:warning("~s, ~s and ~s, oh my!", [lions, tigers, bears])

2011-07-19 18:02:02 [error] <0.31.0>@test2:start:8 oh no! 2011-07-19 18:02:02
[warning] <0.31.0>@test2:start:9 lions, tigers and bears, oh my!

2011-07-19 17:51:21 [error] <0.60.0> gen_server crash terminated with reason: no match
of right hand value {} in crash:handle_call/3
2011-07-19 17:51:22 [error] <0.60.0> CRASH REPORT Process crash with 0 neighbours
crashed with reason: no match of right hand value {} in crash:handle_call/3
RabbitMQ

 ● Используется для взаимодействия узлов
   распределенных систем
 ● Persistent messaging
 ● Полная поддержка протокола AMQP
 ● Кроссплатформенный
 ● Клиенты на всех популярных языках
 ● Используется в продакшне сотнями компаний (включая
   Echo и Mochi Media)

gen_bunny – библиотека для удобной работы с RabbitMQ в
эрланге
Agner

http://erlagner.org

На сегодняшний день 131 пакет

More Related Content

Erlang tasty & useful stuff

  • 2. Структуры данных ● lists (proplists) ● sets ● dict ● gb_trees ● queue ● orddicts ● ordsets ● digraph ● array
  • 4. gen_server -module(mygenserv). %-behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2]). -export([sync_incr/0, async_incr/0, get_value/0]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []). sync_incr() -> gen_server:call(?MODULE, incr). async_incr() -> gen_server:cast(?MODULE, incr). get_value() -> gen_server:call(?MODULE, get_value). init(I) -> State = I, {ok, State}. handle_call(get_value, _From, State) -> {reply, State, State}. handle_call(incr, _From, State) -> {reply, State, State + 1}. handle_cast(incr, State) -> {noreply, State + 1}.
  • 5. supervisor -module(myapp_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init(_) -> MyGenServSpec = { mygenserv, {mygenserv, start_link, []}, permanent, 5000, worker, [mygenserv] }, ChildSpecs = [MyGenServSpec] {ok, {one_for_one, 100, 1}, ChildSpecs}.
  • 6. Хранилища и БД из коробки ● ETS – in-memory хранилище ● DETS – дисковое хранилище ● Mnesia – распределенная база данных на базе ETS&DETS
  • 7. rebar # git clone https://github.com/basho/rebar # cd rebar # make # cp rebar ~/src/myproject # cd ~/src/myproject
  • 8. rebar.config {deps, [ {mochiweb, "v1.1", {git, "https://github.com/mochi/mochiweb", {branch, "master"}} ] }. {erl_opts, [debug_info]}.
  • 9. # ./rebar create-app appid=myapp # ./rebar get-deps # ./rebar compile # erl -pa ebin 1> application:start(myapp).
  • 10. # rebar -c clean Clean compile Compile sources create template= [var=foo,...] Create skel based on template and vars create-app [appid=myapp] Create simple app skel create-node [nodeid=mynode] Create simple node skel list-templates List available templates doc Generate Erlang program documentation check-deps Display to be fetched dependencies get-deps Fetch dependencies update-deps Update fetched dependencies delete-deps Delete fetched dependencies list-deps List dependencies generate [dump_spec=0/1] Build release with reltool generate-upgrade previous_release=path Build an upgrade package generate-appups previous_release=path Generate appup files eunit [suite=foo] Run eunit [test/foo_tests.erl] tests ct [suite=] [case=] Run common_test suites in ./test xref Run cross reference analysis help Show the program options version Show version information
  • 11. Mochiweb git clone https://github.com/mochi/mochiweb ● Легкий высокопроизводительный HTTP-сервер ● mochijson, mochijson2 – Erlang terms в JSON и обратно ● mochiglobal – эмуляция глобальных переменных ● reloader ● Мелкие полезные утилиты (mochinum, mochilists, etc) ● Есть форк с поддержкой websockets
  • 12. mochiweb_http mochiweb_http:start([ {port, 8080}, {ip, "0.0.0.0"}, {loop, fun handle_request/1} ]). handle_request(Req) -> Method = Req:get(method), Path = Req:get(path), GETParams = Req:parse_qs(), POSTParams = Req:parse_post(), Req:ok({"text/html", "ok"}).
  • 13. mochijson2 Props = [ {age, 10}, {name, <<"Snoopy">>}, {talents, [<<"jumping">>, <<"barking">>, <<"sleeping">>]} ], Obj = {struct, Props}, JSON = mochijson2:encode(Obj), Req:ok({"application/json", JSON}). ... 1> mochijson2:decode(<<"{"a": "test"}">>). {struct, [{<<"a">>,<<"test">>}] }
  • 14. reloader # erl -pa ebin -s reloader # vi src/myapp.erl ... # ./rebar compile Reloading myapp ... ok.
  • 15. Другие веб-сервера ● YAWS ● misultin (очень похож на mochiweb, но полегче и попроще) ● cowboy (похож на mochiweb и misultin, но использует не parametrized modules, а callbacks)
  • 16. Riak git clone https://github.com/basho/riak ● riak_core – фреймворк для создания распределенных систем ● riak_error – ограничение размера error reports ● lager – фрймворк для логирования ● basho_bench – утилита для измерения производительности ● rebar
  • 17. lager lager:error("oh no!") lager:warning("~s, ~s and ~s, oh my!", [lions, tigers, bears]) 2011-07-19 18:02:02 [error] <0.31.0>@test2:start:8 oh no! 2011-07-19 18:02:02 [warning] <0.31.0>@test2:start:9 lions, tigers and bears, oh my! 2011-07-19 17:51:21 [error] <0.60.0> gen_server crash terminated with reason: no match of right hand value {} in crash:handle_call/3 2011-07-19 17:51:22 [error] <0.60.0> CRASH REPORT Process crash with 0 neighbours crashed with reason: no match of right hand value {} in crash:handle_call/3
  • 18. RabbitMQ ● Используется для взаимодействия узлов распределенных систем ● Persistent messaging ● Полная поддержка протокола AMQP ● Кроссплатформенный ● Клиенты на всех популярных языках ● Используется в продакшне сотнями компаний (включая Echo и Mochi Media) gen_bunny – библиотека для удобной работы с RabbitMQ в эрланге