From 063393987ad5010fac0dc88b1237d3de9694ed44 Mon Sep 17 00:00:00 2001 From: "T. Thyer" Date: Wed, 7 Mar 2018 02:23:38 -0800 Subject: [PATCH] Add option to balance load between master node and replica nodes (#729) * Add option to balance load between master node and replica nodes --- cluster.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/cluster.go b/cluster.go index ba562cf1..319f1e2c 100644 --- a/cluster.go +++ b/cluster.go @@ -34,6 +34,8 @@ type ClusterOptions struct { ReadOnly bool // Allows routing read-only commands to the closest master or slave node. RouteByLatency bool + // Allows routing read-only commands to the random master or slave node. + RouteRandomly bool // Following options are copied from Options struct. @@ -473,6 +475,12 @@ func (c *clusterState) slotClosestNode(slot int) (*clusterNode, error) { return node, nil } +func (c *clusterState) slotRandomNode(slot int) *clusterNode { + nodes := c.slotNodes(slot) + n := rand.Intn(len(nodes)) + return nodes[n] +} + func (c *clusterState) slotNodes(slot int) []*clusterNode { if slot >= 0 && slot < len(c.slots) { return c.slots[slot] @@ -639,6 +647,11 @@ func (c *ClusterClient) cmdSlotAndNode(cmd Cmder) (int, *clusterNode, error) { return slot, node, err } + if c.opt.RouteRandomly { + node := state.slotRandomNode(slot) + return slot, node, nil + } + node, err := state.slotSlaveNode(slot) return slot, node, err }