Redis集成 #

一、安装配置 #

1.1 安装依赖 #

bash
go get github.com/redis/go-redis/v9

1.2 连接Redis #

go
package cache

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

func NewRedisClient(addr string) *redis.Client {
    return redis.NewClient(&redis.Options{
        Addr:     addr,
        Password: "",
        DB:       0,
    })
}

二、基本操作 #

2.1 字符串操作 #

go
// 设置值
func Set(ctx context.Context, rdb *redis.Client, key string, value interface{}, expiration time.Duration) error {
    return rdb.Set(ctx, key, value, expiration).Err()
}

// 获取值
func Get(ctx context.Context, rdb *redis.Client, key string) (string, error) {
    return rdb.Get(ctx, key).Result()
}

// 删除
func Delete(ctx context.Context, rdb *redis.Client, keys ...string) error {
    return rdb.Del(ctx, keys...).Err()
}

2.2 Hash操作 #

go
// 设置Hash
func HSet(ctx context.Context, rdb *redis.Client, key string, values ...interface{}) error {
    return rdb.HSet(ctx, key, values...).Err()
}

// 获取Hash
func HGet(ctx context.Context, rdb *redis.Client, key, field string) (string, error) {
    return rdb.HGet(ctx, key, field).Result()
}

// 获取所有Hash
func HGetAll(ctx context.Context, rdb *redis.Client, key string) (map[string]string, error) {
    return rdb.HGetAll(ctx, key).Result()
}

三、缓存应用 #

3.1 缓存中间件 #

go
func CacheMiddleware(rdb *redis.Client, ttl time.Duration) fiber.Handler {
    return func(c *fiber.Ctx) error {
        if c.Method() != fiber.MethodGet {
            return c.Next()
        }
        
        key := "cache:" + c.Path()
        
        // 尝试从缓存获取
        cached, err := rdb.Get(context.Background(), key).Result()
        if err == nil {
            c.Set("X-Cache", "HIT")
            return c.SendString(cached)
        }
        
        // 执行请求
        err = c.Next()
        if err != nil {
            return err
        }
        
        // 缓存响应
        body := string(c.Response().Body())
        rdb.Set(context.Background(), key, body, ttl)
        c.Set("X-Cache", "MISS")
        
        return nil
    }
}

3.2 缓存辅助函数 #

go
func GetOrSet(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration, fn func() (string, error)) (string, error) {
    // 尝试从缓存获取
    cached, err := rdb.Get(ctx, key).Result()
    if err == nil {
        return cached, nil
    }
    
    // 执行函数获取数据
    value, err := fn()
    if err != nil {
        return "", err
    }
    
    // 缓存数据
    rdb.Set(ctx, key, value, ttl)
    
    return value, nil
}

四、会话存储 #

4.1 Redis会话存储 #

go
import (
    "github.com/gofiber/fiber/v2/middleware/session"
    "github.com/gofiber/storage/redis"
)

func NewSessionStore(rdb *redis.Client) *session.Store {
    storage := redis.New(redis.Config{
        Host: "localhost",
        Port: 6379,
    })
    
    return session.New(session.Config{
        Storage:    storage,
        Expiration: 24 * time.Hour,
    })
}

五、总结 #

6.1 Redis应用场景 #

场景 说明
缓存 提高响应速度
会话 分布式会话
限流 请求计数
排行榜 有序集合

6.2 下一步 #

现在你已经掌握了Redis集成,接下来让我们学习 MongoDB集成,了解文档数据库的使用!

最后更新:2026-03-28