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) }