golang 从redis cluster获取所有keys

使用 ForEachMaster 即可,如果从Slave获取有可能会有重复的需要另外去重。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func GetKeysWithPrefixForCluster(rdb redis.ClusterClient, ctx context.Context, prefix string) (keys []string, err error) {
	// 从所有主节点中依次获取
	err = rdb.ForEachMaster(ctx, func(ctx context.Context, shard *redis.Client) (err error) {
		thisKeys, err := shard.Keys(ctx, prefix+"*").Result()
		if err != nil {
			return err
		}
		keys = append(keys, thisKeys...)
		return nil
	})
	if err != nil {
		log.Println("GetKeysWithPrefixForCluster err:", err)
		return keys, nil
	}
    //keys=unique(keys)
	return keys, nil
}

去重复

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func unique(slice []string) []string {
	keysMap := make(map[string]bool)
	var uniqueKeys []string
	for _, entry := range slice {
		if _, value := keysMap[entry]; !value {
			keysMap[entry] = true
			uniqueKeys = append(uniqueKeys, entry)
		}
	}
	return uniqueKeys
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计