Skip to content

Commit 6fc6c73

Browse files
committed
Sort slaves to pick 127.0.0.1 first where possible
1 parent dffbfd1 commit 6fc6c73

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

lib/resty/redis/connector.lua

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ local ngx_ERR = ngx.ERR
1111
local ngx_re_match = ngx.re.match
1212
local tbl_insert = table.insert
1313
local tbl_remove = table.remove
14+
local tbl_sort = table.sort
1415

1516
local ok, tbl_new = pcall(require, "table.new")
1617
if not ok then
@@ -95,7 +96,7 @@ end
9596

9697
function _M.connect(self, params)
9798
-- If we have nothing, assume default host connection options apply
98-
if not params then
99+
if not params or type(params) ~= "table" then
99100
params = {}
100101
end
101102

@@ -117,6 +118,15 @@ function _M.connect(self, params)
117118
end
118119

119120

121+
local function sort_by_localhost(a, b)
122+
if a.host == "127.0.0.1" then
123+
return true
124+
else
125+
return false
126+
end
127+
end
128+
129+
120130
function _M.connect_via_sentinel(self, sentinels, master_name, role)
121131
local sentnl, err, previous_errors = self:try_hosts(sentinels)
122132
if not sentnl then
@@ -146,6 +156,9 @@ function _M.connect_via_sentinel(self, sentinels, master_name, role)
146156
return nil, err
147157
end
148158

159+
-- Put any slaves on 127.0.0.1 at the front
160+
tbl_sort(slaves, sort_by_localhost)
161+
149162
local slave, err, previous_errors = self:try_hosts(slaves)
150163
if not slave then
151164
return nil, err, previous_errors
@@ -159,6 +172,7 @@ end
159172
-- the last error received, and previous_errors is a table of the previous errors.
160173
function _M.try_hosts(self, hosts)
161174
local errors = tbl_new(#hosts, 0)
175+
162176
for i, host in ipairs(hosts) do
163177
local r
164178
r, errors[i] = self:connect_to_host(host)

0 commit comments

Comments
 (0)