Skip to content

Instantly share code, notes, and snippets.

@xesina
Last active September 25, 2025 09:11
Show Gist options
  • Select an option

  • Save xesina/9c95e5d7c9508fd5dd03c20b1363c903 to your computer and use it in GitHub Desktop.

Select an option

Save xesina/9c95e5d7c9508fd5dd03c20b1363c903 to your computer and use it in GitHub Desktop.
A script to test redis SCAN
module test-scan
go 1.16
require github.com/go-redis/redis/v8 v8.11.0
package main
import (
"context"
"fmt"
"os"
"time"
"log"
"github.com/go-redis/redis/v8"
)
func main() {
address := os.Getenv("REDIS_ADDRESS")
password := os.Getenv("REDIS_PASSWORD")
if address == "" || password == "" {
log.Println("REDIS_ADDRESS and REDIS_PASSWORD environment variables should be set")
os.Exit(1)
}
start := time.Now()
client := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{
address,
},
Password: password,
DialTimeout: time.Second * 10,
ReadTimeout: time.Second * 10,
IdleTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
})
client.Ping(context.Background())
keys, err := getAllKeysMatched(context.Background(), client, "fhcID|v2|779c104b7c4e166f0be769de65272ae5|*")
if err != nil {
panic(err)
}
elapsed := time.Since(start)
fmt.Printf("Time elapsed to SCAN all keys: %s, keys found: %+v\n", elapsed, keys)
}
func getAllKeysMatched(ctx context.Context, client *redis.ClusterClient, pattern string) (keys []string, err error) {
log.Printf("scanning for all the keys matched with: %s\n", pattern)
nodeIndex := 0
err = client.ForEachMaster(ctx, func(ctx context.Context, rd *redis.Client) error {
nodeIndex++
log.Printf("scan node #%d", nodeIndex)
iter := client.Scan(ctx, 0, pattern, 0).Iterator()
for iter.Next(ctx) {
key := iter.Val()
log.Printf("key found: %s", key)
keys = append(keys, key)
}
if err := iter.Err(); err != nil {
log.Printf("scan iterator has failed: %s", err)
}
return iter.Err()
})
if err != nil {
log.Printf("scanning redis cluster nodes with iterator has failed: %s", err)
return nil, err
}
return keys, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment