Sobes.tech
Senior

How have you used Redis?

sobes.tech AI

Answer from AI

In Go, Redis is often used as a fast in-memory storage for caching, session management, queue implementation, and state storage.

Example of using Redis in Go:

  • Caching database query results
  • Storing counters and limits (rate limiting)
  • Implementing distributed locks

Example code using the popular go-redis library:

import (
    "context"
    "github.com/go-redis/redis/v8"
    "time"
)

func example() error {
    ctx := context.Background()
    rdb := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        Password: "", // no password set
        DB: 0,  // use default DB
    })

    // Set a key with TTL
    err := rdb.Set(ctx, "key", "value", 10*time.Minute).Err()
    if err != nil {
        return err
    }

    // Get the value
    val, err := rdb.Get(ctx, "key").Result()
    if err == redis.Nil {
        // key not found
    } else if err != nil {
        return err
    } else {
        // use val
    }

    return nil
}

Thus, Redis in Go is used to improve performance and simplify architecture by providing fast data access and supporting various data structures.

How have you used Redis? — Golang - sobes.tech