worker_pool的例子

时间:2022-06-01 22:11:16

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

my_pool.erl

 -module(my_pool).

 -export([start/, stop/]).
-export([my_overrun_handler/,do_test/,do_crash/]). start()->
wpool:start(),
start_pool(),
ok. stop()->
stop_pool(),
wpool:stop(),
ok. start_pool()->
wpool:start_sup_pool(my_pool,
[
{overrun_warning,},
{
overrun_handler,{?MODULE,my_overrun_handler}
},
{workers, },
{worker, {test_worker, []}}
]
),
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/, format_status/]).
-export([init/, handle_call/, handle_cast/,handle_info/, terminate/, code_change/]). -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) ->
= ,
{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).