From 711df7ff8d5b9c65f1d1c8e406d5867995fe6922 Mon Sep 17 00:00:00 2001 From: Bhawani Singh Date: Mon, 13 May 2024 13:43:06 +0530 Subject: [PATCH] added readFromAny(master+replica) for better resource utilization --- sentinel.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/sentinel.go b/sentinel.go index 188f88494..f5892e2cc 100644 --- a/sentinel.go +++ b/sentinel.go @@ -45,6 +45,9 @@ type FailoverOptions struct { // Route all commands to replica read-only nodes. ReplicaOnly bool + //Route all read-only commands to master + replica nodes. + ReadFromAny bool + // Use replicas disconnected with master when cannot get connected replicas // Now, this option only works in RandomReplicaAddr function. UseDisconnectedReplicas bool @@ -259,6 +262,8 @@ func masterReplicaDialer( if failover.opt.ReplicaOnly { addr, err = failover.RandomReplicaAddr(ctx) + } else if failover.opt.ReadFromAny { + addr, err = failover.RandomAddr(ctx) } else { addr, err = failover.MasterAddr(ctx) if err == nil { @@ -509,6 +514,30 @@ func (c *sentinelFailover) RandomReplicaAddr(ctx context.Context) (string, error return addresses[rand.Intn(len(addresses))], nil } +func (c *sentinelFailover) RandomAddr(ctx context.Context) (string, error) { + if c.opt == nil { + return "", errors.New("opt is nil") + } + + addresses, err := c.replicaAddrs(ctx, false) + if err != nil { + return "", err + } + + if len(addresses) == 0 && c.opt.UseDisconnectedReplicas { + addresses, err = c.replicaAddrs(ctx, true) + if err != nil { + return "", err + } + } + + masterAdd, _ := c.MasterAddr(ctx) + addresses = append(addresses, masterAdd) + + add := addresses[rand.Intn(len(addresses))] + return add, nil +} + func (c *sentinelFailover) MasterAddr(ctx context.Context) (string, error) { c.mu.RLock() sentinel := c.sentinel