From 8770fc98e1c3fb42a3341f64107e77df76b2b7ca Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Sun, 23 Apr 2017 11:54:56 +0300 Subject: [PATCH] Use round-robin algorithm when selecting worker from DB pool --- src/ejabberd_redis.erl | 2 +- src/ejabberd_riak_sup.erl | 7 ++----- src/ejabberd_sql_sup.erl | 4 +++- src/randoms.erl | 7 ++++++- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/ejabberd_redis.erl b/src/ejabberd_redis.erl index bd85f0ee5..7757c6df3 100644 --- a/src/ejabberd_redis.erl +++ b/src/ejabberd_redis.erl @@ -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()}. diff --git a/src/ejabberd_riak_sup.erl b/src/ejabberd_riak_sup.erl index f5c8f7e4f..a01f3538a 100644 --- a/src/ejabberd_riak_sup.erl +++ b/src/ejabberd_riak_sup.erl @@ -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"). @@ -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) -> diff --git a/src/ejabberd_sql_sup.erl b/src/ejabberd_sql_sup.erl index 09aceafb4..d778e32b7 100644 --- a/src/ejabberd_sql_sup.erl +++ b/src/ejabberd_sql_sup.erl @@ -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) -> diff --git a/src/randoms.erl b/src/randoms.erl index ea21b4a1d..35a5d7580 100644 --- a/src/randoms.erl +++ b/src/randoms.erl @@ -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). @@ -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. -- 2.40.0