2024-11-09 14:59:27 +08:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2025-01-21 14:37:34 +08:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2024-11-09 14:59:27 +08:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
)
|
|
|
|
|
|
|
|
var RDB *redis.Client
|
|
|
|
|
|
|
|
// 连接到 redis
|
|
|
|
func ConnectToRedis(dsn string) *redis.Client {
|
|
|
|
opt, err := redis.ParseURL(dsn)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rdb := redis.NewClient(opt)
|
|
|
|
RDB = rdb
|
|
|
|
return rdb
|
|
|
|
}
|
|
|
|
|
|
|
|
func RedisRemember(key string, timeout int, funct func() interface{}) string {
|
|
|
|
ctx := context.Background()
|
|
|
|
if RDB.Exists(ctx, key).Val() == 0 {
|
|
|
|
data := funct()
|
2025-01-21 14:37:34 +08:00
|
|
|
b, _ := json.Marshal(data)
|
|
|
|
s := RDB.Set(ctx, key, string(b), time.Duration(timeout)*time.Second)
|
|
|
|
if s.Err() != nil {
|
|
|
|
fmt.Printf("s.Err(): %v\n", s.Err())
|
|
|
|
}
|
2024-11-09 14:59:27 +08:00
|
|
|
return RDB.Get(ctx, key).Val()
|
|
|
|
}
|
|
|
|
return RDB.Get(ctx, key).Val()
|
|
|
|
}
|
2025-01-21 14:37:34 +08:00
|
|
|
|
|
|
|
func RedisForget(key string) {
|
|
|
|
ctx := context.Background()
|
|
|
|
RDB.Del(ctx, key)
|
|
|
|
}
|
|
|
|
|
|
|
|
func RedisRememberRet(key string, timeout int, funct func() interface{}, ret interface{}) {
|
|
|
|
s := RedisRemember(key, timeout, funct)
|
|
|
|
json.Unmarshal([]byte(s), ret)
|
|
|
|
}
|