当前位置: 首页 > 工具软件 > Worker Pool > 使用案例 >

worker_pool的例子

蒯胜泫
2023-12-01

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

my_pool.erl

 1 -module(my_pool).
 2 
 3 -export([start/0, stop/0]).
 4 -export([my_overrun_handler/1,do_test/0,do_crash/0]).
 5 
 6 start()->
 7   wpool:start(),
 8   start_pool(),
 9   ok.
10 
11 stop()->
12   stop_pool(),
13   wpool:stop(),
14   ok.
15 
16 start_pool()->
17   wpool:start_sup_pool(my_pool,
18     [
19       {overrun_warning,5000},
20       {
21         overrun_handler,{?MODULE,my_overrun_handler}
22       },
23       {workers, 2},
24       {worker, {test_worker, [11111]}}
25     ]
26   ),
27   ok.
28 
29 stop_pool()->
30   wpool:stop_pool(my_pool),
31   ok.
32 
33 my_overrun_handler(Report) ->
34   io:format("my_overrun_handler ~p~n", [Report]).
35 
36 do_test()->
37   wpool:call(my_pool,{info},best_worker).
38 
39 do_crash()->
40   wpool:call(my_pool,{crash},best_worker).

 

test_worker.erl

 1 -module(test_worker).
 2 
 3 -behaviour(gen_server).
 4 
 5 -export([start_link/1, format_status/2]).
 6 -export([init/1, handle_call/3, handle_cast/2,handle_info/2, terminate/2, code_change/3]).
 7 
 8 -record(state, {}).
 9 
10 start_link([Args]) ->
11   gen_server:start_link(?MODULE, [Args], []).
12 
13 init([Args]) ->
14   io:format("working thread init ~p,~p~n", [self(), Args]),
15   process_flag(trap_exit, true),
16   {ok, #state{}}.
17 
18 handle_call({info}, _From, State) ->
19   io:format("info~n"),
20   {reply, _Reply = ok, State};
21 handle_call({crash}, _From, _State) ->
22   1 = 2,
23 {noreply, crash};
24 handle_call(_Request, _From, State) ->
25 {reply, _Reply = ok, State}.
26 
27 handle_cast(_Msg, State) ->
28   {noreply, State}.
29 
30 handle_info({'EXIT', _Pid, Reason}, State) ->
31   io:format("exit reason ~p~n", [Reason]),
32   case Reason of
33     normal ->
34       io:format("normal exit trapped~n"),
35       {stop, normal, State};
36     other ->
37       io:format("other exit trapped~n"),
38       {noreply, State}
39   end;
40 handle_info(_Info, State) ->
41   {noreply, State}.
42 
43 terminate(_Reason, _State) ->
44   io:format("terminate ~p,~p,~p~n", [_Reason, _State, self()]),
45   ok.
46 
47 code_change(_OldVsn, State, _Extra) ->
48   {ok, State}.
49 
50 format_status(_Opt, _StatusData) ->
51   erlang:error(not_implemented).

 

转载于:https://www.cnblogs.com/ziyouchutuwenwu/p/4881075.html

 类似资料: