Skip to content

Commit e9fef17

Browse files
authored
Merge pull request #1581 from prathik/replica-cmd
Add support to get cluster replica node for a given key
2 parents 80d2961 + fd6643d commit e9fef17

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

cluster.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1655,6 +1655,35 @@ func (c *ClusterClient) slotMasterNode(ctx context.Context, slot int) (*clusterN
16551655
return state.slotMasterNode(slot)
16561656
}
16571657

1658+
// ReplicaForKey gets a client for a replica node to run any command on it.
1659+
// This is especially useful if we want to run a particular lua script which has
1660+
// only read only commands on the replica.
1661+
// This is because other redis commands generally have a flag that points that
1662+
// they are read only and automatically run on the replica nodes
1663+
// if ClusterOptions.ReadOnly flag is set to true.
1664+
func (c *ClusterClient) ReplicaForKey(ctx context.Context, key string) (*Client, error) {
1665+
state, err := c.state.Get(ctx)
1666+
if err != nil {
1667+
return nil, err
1668+
}
1669+
slot := hashtag.Slot(key)
1670+
node, err := c.slotReadOnlyNode(state, slot)
1671+
if err != nil {
1672+
return nil, err
1673+
}
1674+
return node.Client, err
1675+
}
1676+
1677+
// MasterForKey return a client to the master node for a particular key.
1678+
func (c *ClusterClient) MasterForKey(ctx context.Context, key string) (*Client, error) {
1679+
slot := hashtag.Slot(key)
1680+
node, err := c.slotMasterNode(ctx, slot)
1681+
if err != nil {
1682+
return nil, err
1683+
}
1684+
return node.Client, err
1685+
}
1686+
16581687
func appendUniqueNode(nodes []*clusterNode, node *clusterNode) []*clusterNode {
16591688
for _, n := range nodes {
16601689
if n == node {

cluster_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,6 +864,20 @@ var _ = Describe("ClusterClient", func() {
864864
}))
865865
})
866866

867+
It("should return correct replica for key", func() {
868+
client, err := client.ReplicaForKey(ctx, "test")
869+
Expect(err).ToNot(HaveOccurred())
870+
info := client.Info(ctx, "server")
871+
Expect(info.Val()).Should(ContainSubstring("tcp_port:8224"))
872+
})
873+
874+
It("should return correct master for key", func() {
875+
client, err := client.MasterForKey(ctx, "test")
876+
Expect(err).ToNot(HaveOccurred())
877+
info := client.Info(ctx, "server")
878+
Expect(info.Val()).Should(ContainSubstring("tcp_port:8221"))
879+
})
880+
867881
assertClusterClient()
868882
})
869883

0 commit comments

Comments
 (0)