58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
// cache.go
|
|
package cache
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"time"
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
)
|
|
|
|
var redisClient *redis.Client
|
|
|
|
func NewRedisClient() *redis.Client {
|
|
if redisClient == nil {
|
|
redisClient = redis.NewClient(&redis.Options{
|
|
Addr: "localhost:6379",
|
|
Password: "", // 无密码
|
|
DB: 0, // 默认数据库
|
|
})
|
|
|
|
// 测试连接
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
_, err := redisClient.Ping(ctx).Result()
|
|
if err != nil {
|
|
panic("Redis连接失败: " + err.Error())
|
|
}
|
|
}
|
|
|
|
return redisClient
|
|
}
|
|
|
|
// SetSecondCacheObject 设置二级缓存
|
|
func SetSecondCacheObject(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
|
client := NewRedisClient()
|
|
|
|
jsonData, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return client.Set(ctx, key, jsonData, expiration).Err()
|
|
}
|
|
|
|
// GetSecondCacheObject 获取二级缓存
|
|
func GetSecondCacheObject(ctx context.Context, key string, result interface{}) error {
|
|
client := NewRedisClient()
|
|
|
|
data, err := client.Get(ctx, key).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return json.Unmarshal([]byte(data), result)
|
|
}
|