Skip to content

Commit 9696b2d

Browse files
committed
Rotate slaves
1 parent 03dff6d commit 9696b2d

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

lib/resty/redis/connector.lua

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ local DEFAULTS = setmetatable({
126126
master_name = "mymaster",
127127
role = "master", -- master | slave
128128
sentinels = {},
129+
rotate_slaves = false,
130+
slave_rr_counter = 0,
129131

130132
-- Redis proxies typically don't support full Redis capabilities
131133
connection_is_proxied = false,
@@ -262,6 +264,20 @@ function _M.connect(self, params)
262264
end
263265

264266

267+
local function rotate_slaves(self, slaves)
268+
local slaves_length = #slaves
269+
local rotated_slaves = tbl_new(slaves_length, 0)
270+
local local_rr_counter = (self.config.slave_rr_counter + 1) % slaves_length
271+
self.config.slave_rr_counter = local_rr_counter
272+
273+
for i, _ in ipairs(slaves) do
274+
local_rr_counter = (local_rr_counter % slaves_length) + 1
275+
rotated_slaves[i] = slaves[local_rr_counter]
276+
end
277+
278+
return rotated_slaves
279+
end
280+
265281
local function sort_by_localhost(a, b)
266282
if a.host == "127.0.0.1" and b.host ~= "127.0.0.1" then
267283
return true
@@ -319,6 +335,9 @@ function _M.connect_via_sentinel(self, params)
319335

320336
sentnl:set_keepalive()
321337

338+
if params.rotate_slaves then
339+
slaves = rotate_slaves(self, slaves)
340+
end
322341
-- Put any slaves on 127.0.0.1 at the front
323342
tbl_sort(slaves, sort_by_localhost)
324343

0 commit comments

Comments
 (0)