Skip to content

Commit

Permalink
Use round-robin algorithm when selecting worker from DB pool
Browse files Browse the repository at this point in the history
  • Loading branch information
zinid committed Apr 23, 2017
1 parent 18433e2 commit 8770fc9
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/ejabberd_redis.erl
Expand Up @@ -516,7 +516,7 @@ log_error(Cmd, Reason) ->

-spec get_rnd_id() -> pos_integer().
get_rnd_id() ->
randoms:uniform(2, ejabberd_redis_sup:get_pool_size()).
randoms:round_robin(ejabberd_redis_sup:get_pool_size() - 1) + 2.

-spec get_result([{error, atom() | binary()} | {ok, iodata()}]) ->
{ok, [redis_reply()]} | {error, binary()}.
Expand Down
7 changes: 2 additions & 5 deletions src/ejabberd_riak_sup.erl
Expand Up @@ -30,7 +30,7 @@
-author('alexey@process-one.net').

-export([start_link/0, init/1, get_pids/0,
transform_options/1, get_random_pid/0, get_random_pid/1,
transform_options/1, get_random_pid/0,
host_up/1, config_reloaded/0, opt_type/1]).

-include("ejabberd.hrl").
Expand Down Expand Up @@ -199,10 +199,7 @@ get_pids() ->
[ejabberd_riak:get_proc(I) || I <- lists:seq(1, get_pool_size())].

get_random_pid() ->
get_random_pid(p1_time_compat:system_time()).

get_random_pid(Term) ->
I = erlang:phash2(Term, get_pool_size()) + 1,
I = randoms:round_robin(get_pool_size()) + 1,
ejabberd_riak:get_proc(I).

transform_options(Opts) ->
Expand Down
4 changes: 3 additions & 1 deletion src/ejabberd_sql_sup.erl
Expand Up @@ -98,7 +98,9 @@ get_pids(Host) ->
get_random_pid(Host) ->
case get_pids(Host) of
[] -> none;
Pids -> lists:nth(erlang:phash(p1_time_compat:unique_integer(), length(Pids)), Pids)
Pids ->
I = randoms:round_robin(length(Pids)) + 1,
lists:nth(I, Pids)
end.

add_pid(Host, Pid) ->
Expand Down
7 changes: 6 additions & 1 deletion src/randoms.erl
Expand Up @@ -27,7 +27,8 @@

-author('alexey@process-one.net').

-export([get_string/0, uniform/0, uniform/1, uniform/2, bytes/1]).
-export([get_string/0, uniform/0, uniform/1, uniform/2, bytes/1,
round_robin/1]).

-define(THRESHOLD, 16#10000000000000000).

Expand All @@ -51,3 +52,7 @@ bytes(N) ->
bytes(N) ->
crypto:rand_bytes(N).
-endif.

-spec round_robin(pos_integer()) -> non_neg_integer().
round_robin(N) ->
erlang:unique_integer([monotonic, positive]) rem N.

0 comments on commit 8770fc9

Please sign in to comment.