example/cluster-mget/README.md
This example demonstrates how to use the Redis Cluster client with the MGET command to retrieve multiple keys efficiently.
The example shows:
SET commandsMGETYou need a running Redis Cluster. The example expects cluster nodes at:
localhost:7000localhost:7001localhost:7002If you don't have a Redis Cluster running, you can use the docker-compose setup from the repository root:
# From the go-redis repository root
docker compose --profile cluster up -d
This will start a Redis Cluster with nodes on ports 16600-16605.
If using the docker-compose cluster, update the Addrs in main.go to:
Addrs: []string{
"localhost:16600",
"localhost:16601",
"localhost:16602",
},
go run main.go
✓ Connected to Redis cluster
=== Setting 10 keys ===
✓ SET key0 = value0
✓ SET key1 = value1
✓ SET key2 = value2
✓ SET key3 = value3
✓ SET key4 = value4
✓ SET key5 = value5
✓ SET key6 = value6
✓ SET key7 = value7
✓ SET key8 = value8
✓ SET key9 = value9
=== Retrieving keys with MGET ===
=== Validating MGET results ===
✓ key0: value0
✓ key1: value1
✓ key2: value2
✓ key3: value3
✓ key4: value4
✓ key5: value5
✓ key6: value6
✓ key7: value7
✓ key8: value8
✓ key9: value9
=== Summary ===
✓ All values retrieved successfully and match expected values!
=== Cleaning up ===
✓ Cleanup complete
MGET (Multiple GET) is a Redis command that retrieves the values of multiple keys in a single operation. This is more efficient than executing multiple individual GET commands.
Syntax:
result, err := rdb.MGet(ctx, key1, key2, key3, ...).Result()
Returns:
interface{} valuesnil is returned for keys that don't existThe ClusterClient automatically handles:
For MGET operations in a cluster, the client may need to split the request across multiple nodes if the keys map to different hash slots.
// Create cluster client
rdb := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{
"localhost:7000",
"localhost:7001",
"localhost:7002",
},
})
// Set individual keys
for i := 0; i < 10; i++ {
err := rdb.Set(ctx, fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i), 0).Err()
// handle error
}
// Retrieve all keys with MGET
result, err := rdb.MGet(ctx, keys...).Result()
// Validate results
for i, val := range result {
actualValue, ok := val.(string)
// validate actualValue matches expected
}