Add option to balance load between master node and replica nodes (#729)

* Add option to balance load between master node and replica nodes
This commit is contained in:
T. Thyer 2018-03-07 02:23:38 -08:00 committed by Vladimir Mihailenco
parent 852a60d520
commit 063393987a
1 changed files with 13 additions and 0 deletions

View File

@ -34,6 +34,8 @@ type ClusterOptions struct {
ReadOnly bool ReadOnly bool
// Allows routing read-only commands to the closest master or slave node. // Allows routing read-only commands to the closest master or slave node.
RouteByLatency bool RouteByLatency bool
// Allows routing read-only commands to the random master or slave node.
RouteRandomly bool
// Following options are copied from Options struct. // Following options are copied from Options struct.
@ -473,6 +475,12 @@ func (c *clusterState) slotClosestNode(slot int) (*clusterNode, error) {
return node, nil 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 { func (c *clusterState) slotNodes(slot int) []*clusterNode {
if slot >= 0 && slot < len(c.slots) { if slot >= 0 && slot < len(c.slots) {
return c.slots[slot] return c.slots[slot]
@ -639,6 +647,11 @@ func (c *ClusterClient) cmdSlotAndNode(cmd Cmder) (int, *clusterNode, error) {
return slot, node, err return slot, node, err
} }
if c.opt.RouteRandomly {
node := state.slotRandomNode(slot)
return slot, node, nil
}
node, err := state.slotSlaveNode(slot) node, err := state.slotSlaveNode(slot)
return slot, node, err return slot, node, err
} }