Connect to Redis

Use the official `go-redis/redis` library to connect to Redis by initializing a client with your server address and authentication details, then verify the connection with a simple `Ping` command.

Use the official go-redis/redis library to connect to Redis by initializing a client with your server address and authentication details, then verify the connection with a simple Ping command. This approach handles connection pooling and error handling automatically, making it the standard for production Go applications.

Here is a complete, runnable example using the latest v9 API:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

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

func main() {
	ctx := context.Background()

	// Initialize the client
	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379", // Redis server address
		Password: "",               // No password by default
		DB:       0,                // Use default DB
	})

	// Verify connection immediately
	if err := rdb.Ping(ctx).Err(); err != nil {
		log.Fatalf("failed to connect to Redis: %v", err)
	}

	// Example: Set and Get a value
	if err := rdb.Set(ctx, "greeting", "Hello, Go!", time.Hour).Err(); err != nil {
		log.Fatalf("failed to set key: %v", err)
	}

	val, err := rdb.Get(ctx, "greeting").Result()
	if err != nil {
		log.Fatalf("failed to get key: %v", err)
	}

	fmt.Println("Value from Redis:", val)

	// Always close the client to release resources
	if err := rdb.Close(); err != nil {
		log.Printf("failed to close client: %v", err)
	}
}

If you need to connect to a Redis cluster instead of a standalone instance, switch to redis.NewClusterClient and provide a list of node addresses. The library handles the routing and failover logic for you.

// Cluster connection example
clusterClient := redis.NewClusterClient(&redis.ClusterOptions{
	Addrs:    []string{"localhost:7000", "localhost:7001", "localhost:7002"},
	Password: "",
})

// Verify cluster connection
if err := clusterClient.Ping(ctx).Err(); err != nil {
	log.Fatalf("failed to connect to Redis Cluster: %v", err)
}

For local development, you can skip installing Redis manually by using Docker. Run this command to start a default Redis instance:

docker run -d -p 6379:6379 --name redis-dev redis:latest

Remember to handle context cancellation in your production code to ensure timeouts are respected and connections are properly closed during shutdown. The go-redis client automatically manages connection pooling, so you typically only need one client instance shared across your application rather than creating a new client for every request.