In this post we will present how to use redis KEYS command in a cluster environment and go-redis library.
The go-redis library automatically handled a single key commands such as GET, SET. It recognizes the location of each slot on a relevant master, and address the master (or slave) that hold the specific key.
However, the KEYS command is a multi-keys related, and hence the go-redis does not handle it.
The way to handle it is using the ForEachMaster command, and run the KEYS command on each master, and finally aggregate the result. An example for this is listed below.
func ClusterKeys(client *redis.ClusterClient, pattern string) []string {
allKeys := make([]string, 0)
mutex := sync.Mutex{}
err := client.ForEachMaster(context.Background(), func(ctx context.Context, master *redis.Client) error {
cmd := master.Keys(ctx, pattern)
err := cmd.Err()
if err != nil {
return err
}
value, err := cmd.Result()
if err != nil {
return err
}
mutex.Lock()
allKeys = append(allKeys, value...)
mutex.Unlock()
return nil
})
if err != nil {
panic(err)
}
return allKeys
}
Notice that usage of the redis KEYS command in a production environment is not recommended. You might want to use SCAN command instead. For more details see this post.
No comments:
Post a Comment