Skip to content

Commit 36d4029

Browse files
committed
Set DB for failover cluster client
1 parent 4648432 commit 36d4029

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

sentinel.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,18 @@ func NewFailoverClusterClient(failoverOpt *FailoverOptions) *ClusterClient {
815815
}
816816

817817
opt := failoverOpt.clusterOptions()
818+
if failoverOpt.DB != 0 {
819+
onConnect := opt.OnConnect
820+
821+
opt.OnConnect = func(ctx context.Context, cn *Conn) error {
822+
if err := cn.Select(ctx, failoverOpt.DB).Err(); err != nil {
823+
return err
824+
}
825+
826+
return onConnect(ctx, cn)
827+
}
828+
}
829+
818830
opt.ClusterSlots = func(ctx context.Context) ([]ClusterSlot, error) {
819831
masterAddr, err := failover.MasterAddr(ctx)
820832
if err != nil {

sentinel_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ var _ = Describe("NewFailoverClusterClient", func() {
200200
SentinelAddrs: sentinelAddrs,
201201

202202
RouteRandomly: true,
203+
DB: 1,
203204
})
204205
Expect(client.FlushDB(ctx).Err()).NotTo(HaveOccurred())
205206

@@ -289,6 +290,20 @@ var _ = Describe("NewFailoverClusterClient", func() {
289290
})
290291
})
291292

293+
It("should sentinel cluster client db", func() {
294+
err := client.ForEachShard(ctx, func(ctx context.Context, c *redis.Client) error {
295+
return c.Ping(ctx).Err()
296+
})
297+
Expect(err).NotTo(HaveOccurred())
298+
299+
_ = client.ForEachShard(ctx, func(ctx context.Context, c *redis.Client) error {
300+
clientInfo, err := c.ClientInfo(ctx).Result()
301+
Expect(err).NotTo(HaveOccurred())
302+
Expect(clientInfo.DB).To(Equal(1))
303+
return nil
304+
})
305+
})
306+
292307
It("should sentinel cluster PROTO 3", func() {
293308
_ = client.ForEachShard(ctx, func(ctx context.Context, c *redis.Client) error {
294309
val, err := client.Do(ctx, "HELLO").Result()

0 commit comments

Comments
 (0)