@@ -11,6 +11,7 @@ local ngx_ERR = ngx.ERR
1111local ngx_re_match = ngx .re .match
1212local tbl_insert = table.insert
1313local tbl_remove = table.remove
14+ local tbl_sort = table.sort
1415
1516local ok , tbl_new = pcall (require , " table.new" )
1617if not ok then
9596
9697function _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)
117118end
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+
120130function _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
159172-- the last error received, and previous_errors is a table of the previous errors.
160173function _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