Skip to content

ReadFromAny (master+replica) without cluster mode (Master-Replica setup) #2995

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions sentinel.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -262,6 +265,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 {
Expand Down Expand Up @@ -512,6 +517,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)
Copy link
Preview

Copilot AI Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider handling the error returned by c.MasterAddr(ctx) to ensure that the master address is valid before appending it to the addresses pool.

Suggested change
masterAdd, _ := c.MasterAddr(ctx)
masterAdd, err := c.MasterAddr(ctx)
if err != nil {
return "", err
}

Copilot uses AI. Check for mistakes.

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
Expand Down
Loading