Redis 集群的 Go 客户端

提示

要了解如何使用 go-redis 客户端,请参阅 入门 指南。

go-redis 附带了用于 Redis 集群在新窗口中打开 的客户端。在底层,redis.ClusterClient 使用 redis.Client 与集群中的每个节点进行通信。每个 redis.Client 都维护一个独立的连接池。

连接到 Redis 集群

import "github.com/redis/go-redis/v9"

rdb := redis.NewClusterClient(&redis.ClusterOptions{
    Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},

    // To route commands by latency or randomly, enable one of the following.
    //RouteByLatency: true,
    //RouteRandomly: true,
})

遍历分片

err := rdb.ForEachShard(ctx, func(ctx context.Context, shard *redis.Client) error {
    return shard.Ping(ctx).Err()
})
if err != nil {
    panic(err)
}

要遍历主节点,请使用 ForEachMaster。要遍历从节点,请使用 ForEachSlave

更改某些分片的选项

rdb := redis.NewClusterClient(&redis.ClusterOptions{
    NewClient: func(opt *redis.Options) *redis.NewClient {
        user, pass := userPassForAddr(opt.Addr)
        opt.Username = user
        opt.Password = pass

        return redis.NewClient(opt)
    },
})

另请参阅