您的位置:首页 > 其它

worker_pool的例子

2015-10-14 23:07 169 查看
鉴于poolboy的坑pooler不支持r18,又有在知乎上看到大神推荐worker_pool这个进程池框架(工作者进程在创建时崩溃,worker_pool不受影响),所以研究了下,贴个小例子

my_pool.erl

-module(my_pool).

-export([start/0, stop/0]).
-export([my_overrun_handler/1,do_test/0,do_crash/0]).

start()->
wpool:start(),
start_pool(),
ok.

stop()->
stop_pool(),
wpool:stop(),
ok.

start_pool()->
wpool:start_sup_pool(my_pool,
[
{overrun_warning,5000},
{
overrun_handler,{?MODULE,my_overrun_handler}
},
{workers, 2},
{worker, {test_worker, [11111]}}
]
),
ok.

stop_pool()->
wpool:stop_pool(my_pool),
ok.

my_overrun_handler(Report) ->
io:format("my_overrun_handler ~p~n", [Report]).

do_test()->
wpool:call(my_pool,{info},best_worker).

do_crash()->
wpool:call(my_pool,{crash},best_worker).


test_worker.erl

-module(test_worker).

-behaviour(gen_server).

-export([start_link/1, format_status/2]).
-export([init/1, handle_call/3, handle_cast/2,handle_info/2, terminate/2, code_change/3]).

-record(state, {}).

start_link([Args]) ->
gen_server:start_link(?MODULE, [Args], []).

init([Args]) ->
io:format("working thread init ~p,~p~n", [self(), Args]),
process_flag(trap_exit, true),
{ok, #state{}}.

handle_call({info}, _From, State) ->
io:format("info~n"),
{reply, _Reply = ok, State};
handle_call({crash}, _From, _State) ->
1 = 2,
{noreply, crash};
handle_call(_Request, _From, State) ->
{reply, _Reply = ok, State}.

handle_cast(_Msg, State) ->
{noreply, State}.

handle_info({'EXIT', _Pid, Reason}, State) ->
io:format("exit reason ~p~n", [Reason]),
case Reason of
normal ->
io:format("normal exit trapped~n"),
{stop, normal, State};
other ->
io:format("other exit trapped~n"),
{noreply, State}
end;
handle_info(_Info, State) ->
{noreply, State}.

terminate(_Reason, _State) ->
io:format("terminate ~p,~p,~p~n", [_Reason, _State, self()]),
ok.

code_change(_OldVsn, State, _Extra) ->
{ok, State}.

format_status(_Opt, _StatusData) ->
erlang:error(not_implemented).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: