83 lines
1.9 KiB
Go
83 lines
1.9 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"gitea.zjmud.xyz/phyer/rbac/config"
|
|
"github.com/go-redis/redis/v8"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
RedisClient *redis.Client
|
|
ctx = context.Background()
|
|
)
|
|
|
|
// InitRedis 初始化 Redis 连接
|
|
func InitRedis() error {
|
|
RedisClient = redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%d", config.AppConfig.RedisHost, config.AppConfig.RedisPort),
|
|
Password: config.AppConfig.RedisPassword,
|
|
DB: config.AppConfig.RedisDB, // 使用默认数据库
|
|
})
|
|
|
|
// 测试连接
|
|
_, err := RedisClient.Ping(ctx).Result()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to connect to Redis: %v", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Set 设置键值对,带过期时间
|
|
func Set(key string, value interface{}, expiration time.Duration) error {
|
|
return RedisClient.Set(ctx, key, value, expiration).Err()
|
|
}
|
|
|
|
// Get 获取键值
|
|
func Get(key string) (string, error) {
|
|
return RedisClient.Get(ctx, key).Result()
|
|
}
|
|
|
|
// Delete 删除键
|
|
func Delete(key string) error {
|
|
return RedisClient.Del(ctx, key).Err()
|
|
}
|
|
|
|
// Exists 检查键是否存在
|
|
func Exists(key string) (bool, error) {
|
|
result, err := RedisClient.Exists(ctx, key).Result()
|
|
return result == 1, err
|
|
}
|
|
|
|
// Incr 自增键值
|
|
func Incr(key string) (int64, error) {
|
|
return RedisClient.Incr(ctx, key).Result()
|
|
}
|
|
|
|
// Decr 自减键值
|
|
func Decr(key string) (int64, error) {
|
|
return RedisClient.Decr(ctx, key).Result()
|
|
}
|
|
|
|
// HSet 设置哈希字段值
|
|
func HSet(key string, field string, value interface{}) error {
|
|
return RedisClient.HSet(ctx, key, field, value).Err()
|
|
}
|
|
|
|
// HGet 获取哈希字段值
|
|
func HGet(key string, field string) (string, error) {
|
|
return RedisClient.HGet(ctx, key, field).Result()
|
|
}
|
|
|
|
// HGetAll 获取哈希所有字段值
|
|
func HGetAll(key string) (map[string]string, error) {
|
|
return RedisClient.HGetAll(ctx, key).Result()
|
|
}
|
|
|
|
// Expire 设置键的过期时间
|
|
func Expire(key string, expiration time.Duration) error {
|
|
return RedisClient.Expire(ctx, key, expiration).Err()
|
|
}
|