Skip to content

redis

go
go get github.com/redis/go-redis/v9
go
package cache

import (
	"context"
	"time"

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

var Client *redis.Client

// Init 初始化 Redis 客户端,在 main 启动时调用
func Init(addr, password string, db int) {
	Client = redis.NewClient(&redis.Options{
		Addr:     addr,     // "localhost:6379"
		Password: password, // 无密码填空
		DB:       db,       // 0
	})
}

// Set 写入 string,过期时间 0 表示不过期
func Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
	return Client.Set(ctx, key, value, ttl).Err()
}

// Get 读取 string
func Get(ctx context.Context, key string) (string, error) {
	return Client.Get(ctx, key).Result()
}

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

// Exists 判断 key 是否存在
func Exists(ctx context.Context, keys ...string) (int64, error) {
	return Client.Exists(ctx, keys...).Result()
}