Browse Source

correct way to stop worker

Yuriy Zhloba 9 years ago
parent
commit
3d417d4288
3 changed files with 19 additions and 4 deletions
  1. 3 1
      src/epgsql_pool.erl
  2. 2 1
      src/epgsql_pool_utils.erl
  3. 14 2
      src/epgsql_pool_worker.erl

+ 3 - 1
src/epgsql_pool.erl

@@ -21,7 +21,9 @@ start(PoolName0, InitCount, MaxCount) ->
         {ok, _} -> PoolConfig = [{name, PoolName},
                                  {init_count, InitCount},
                                  {max_count, MaxCount},
-                                 {start_mfa, {epgsql_pool_worker, start_link, [PoolName]}}],
+                                 {start_mfa, {epgsql_pool_worker, start_link, [PoolName]}},
+                                 {stop_mfa, {epgsql_pool_worker, stop, []}}
+                                ],
                    pooler:new_pool(PoolConfig);
         {error, not_found} -> {error, connection_params_not_found}
     end.

+ 2 - 1
src/epgsql_pool_utils.erl

@@ -27,7 +27,8 @@ open_connection(PoolName, Connection0) ->
     end.
 
 
--spec close_connection(#epgsql_connection{}) -> #epgsql_connection{}.
+-spec close_connection(#epgsql_connection{} | undefined) -> #epgsql_connection{}.
+close_connection(undefined) -> undefined;
 close_connection(#epgsql_connection{sock = undefined} = Connection) -> Connection;
 close_connection(#epgsql_connection{sock = Sock} = Connection) ->
     epgsql:close(Sock),

+ 14 - 2
src/epgsql_pool_worker.erl

@@ -2,7 +2,7 @@
 
 -behaviour(gen_server).
 
--export([start_link/1]).
+-export([start_link/1, stop/1]).
 -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
 
 -include("epgsql_pool.hrl").
@@ -23,11 +23,15 @@ start_link(PoolName0) ->
     gen_server:start_link(?MODULE, PoolName, []).
 
 
+-spec stop(pid()) -> ok.
+stop(Pid) ->
+    gen_server:call(Pid, stop).
+
+
 %%% gen_server API
 
 -spec init(gs_args()) -> gs_init_reply().
 init(PoolName) ->
-    error_logger:info_msg("Init epgsql pool worker: ~p", [PoolName]),
     process_flag(trap_exit, true),
     random:seed(now()),
     self() ! open_connection,
@@ -37,6 +41,14 @@ init(PoolName) ->
 
 
 -spec handle_call(gs_request(), gs_from(), gs_reply()) -> gs_call_reply().
+handle_call(stop, _From, #state{connection = Connection,
+                                send_keep_alive_timer = Send_KA_Timer,
+                                no_reply_keep_alive_timer = NR_KA_Timer} = State) ->
+    Connection2 = epgsql_pool_utils:close_connection(Connection),
+    erlang:cancel_timer(Send_KA_Timer),
+    erlang:cancel_timer(NR_KA_Timer),
+    {stop, normal, ok, State#state{connection = Connection2}};
+
 handle_call(_, _From, #state{connection = undefined} = State) ->
     {reply, {error, no_connection}, State};