How to Implement Caching with Redis in Go

Use the go-redis library to connect to a Redis server and store data with Set and retrieve it with Get for fast access.

Implement Redis caching in Go by installing the go-redis client, creating a client instance, and using Set and Get methods to store and retrieve data.

package main

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

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

func main() {
	ctx := context.Background()
	
	// 1. Create Redis client
	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	// 2. Set a key with expiration
	err := rdb.Set(ctx, "user:1", "Alice", 5*time.Minute).Err()
	if err != nil {
		log.Fatal(err)
	}

	// 3. Get the key
	val, err := rdb.Get(ctx, "user:1").Result()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("user:1 is", val)
	
	// 4. Close client
	rdb.Close()
}

Install the library first: go get github.com/redis/go-redis/v9.