59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
// Package redis 提供统一的 Redis 缓存抽象层
|
|
// 支持两种后端:
|
|
// - redka: 内嵌 Redis 兼容存储(零依赖,独立二进制模式)// Logan.Li
|
|
// - redis: 外部 Redis 服务器(Docker / 生产环境)
|
|
//
|
|
// 使用方式:
|
|
//
|
|
// cache, err := redis.New(redis.Config{
|
|
// Driver: "redka", // 或 "redis"
|
|
// Host: "localhost",
|
|
// Port: 6379,
|
|
// Password: "",
|
|
// DB: 0,
|
|
// DataDir: "data/redka", // redka 数据目录(仅 redka 驱动使用)
|
|
// })
|
|
//
|
|
// cache.Set(ctx, "key", "value", 0)
|
|
// val, _ := cache.Get(ctx, "key")
|
|
package redis
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// Config Redis 配置 // Logan.Li
|
|
type Config struct {
|
|
Driver string // "redka" 或 "redis"
|
|
Host string
|
|
Port int
|
|
Password string
|
|
DB int
|
|
DataDir string // redka 数据目录
|
|
}
|
|
|
|
// Cache Redis 缓存接口 // Logan.Li
|
|
type Cache interface {
|
|
Get(ctx context.Context, key string) (string, error)
|
|
Set(ctx context.Context, key string, value string, expiration time.Duration) error
|
|
Del(ctx context.Context, keys ...string) error
|
|
Exists(ctx context.Context, keys ...string) (int64, error)
|
|
Expire(ctx context.Context, key string, expiration time.Duration) error
|
|
Ping(ctx context.Context) error
|
|
Close() error
|
|
}
|
|
|
|
// New 创建缓存实例(根据驱动自动选择后端)// Logan.Li
|
|
func New(cfg Config) (Cache, error) {
|
|
switch cfg.Driver {
|
|
case "redka", "":
|
|
return newRedka(cfg)
|
|
case "redis":
|
|
return newGoRedis(cfg)
|
|
default:
|
|
return nil, fmt.Errorf("redis: 不支持的驱动: %s (支持: redka, redis)", cfg.Driver)
|
|
}
|
|
}
|