YiTao/model/redis.go
wzj 735aad8cc1
All checks were successful
Deploy on Tag / build-and-deploy (push) Successful in 38s
新增:历史记录与推荐接口
2025-01-21 14:37:34 +08:00

49 lines
966 B
Go

package model
import (
"context"
"encoding/json"
"fmt"
"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()
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())
}
return RDB.Get(ctx, key).Val()
}
return RDB.Get(ctx, key).Val()
}
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)
}