| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- package cache
- import (
- "context"
- "errors"
- "fmt"
- "github.com/go-redis/redis/v8"
- "log"
- "strings"
- "sync"
- "time"
- "xps/viewmodels"
- )
- var ErrRedisInit = errors.New("缓存初始化失败")
- var (
- once sync.Once
- cacheClient redis.UniversalClient
- )
- var CONFIG = Redis{
- DB: 0,
- Addr: "127.0.0.1:6379",
- Password: "",
- PoolSize: 0,
- }
- type Redis struct {
- DB int `mapstructure:"db" json:"db" yaml:"db"`
- Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
- Password string `mapstructure:"password" json:"password" yaml:"password"`
- PoolSize int `mapstructure:"pool-size" json:"pool-size" yaml:"pool-size"`
- }
- func init() {
- if Instance() == nil {
- log.Fatal(ErrRedisInit)
- }
- }
- func Instance() redis.UniversalClient {
- once.Do(func() {
- universalOptions := &redis.UniversalOptions{
- Addrs: strings.Split(CONFIG.Addr, ","),
- Password: CONFIG.Password,
- PoolSize: int(CONFIG.PoolSize),
- IdleTimeout: 300 * time.Second,
- }
- cacheClient = redis.NewUniversalClient(universalOptions)
- })
- return cacheClient
- }
- func SetCache(key string, value interface{}, expiration time.Duration) error {
- err := Instance().Set(context.Background(), key, value, expiration).Err()
- if err != nil {
- return err
- }
- return nil
- }
- func GetCache(key string) (interface{}, error) {
- return Instance().Get(context.Background(), key).Result()
- }
- func DeleteCache(key string) (int64, error) {
- return Instance().Del(context.Background(), key).Result()
- }
- func GetCacheString(key string) (string, error) {
- value, err := GetCacheBytes(key)
- if err != nil {
- return "", err
- }
- return string(value), nil
- }
- func GetCacheBytes(key string) ([]byte, error) {
- return Instance().Get(context.Background(), key).Bytes()
- }
- func GetCacheUint(key string) (uint64, error) {
- return Instance().Get(context.Background(), key).Uint64()
- }
- func SetUserData(userId int64, userData *viewmodels.UserData) error {
- keyStr := fmt.Sprintf("user_%d", userId)
- return SetCache(keyStr, userData, 0)
- }
- func GetUserData(userId int64) (*viewmodels.UserData, error) {
- keyStr := fmt.Sprintf("user_%d", userId)
- userData := &viewmodels.UserData{}
- err := Instance().Get(context.Background(), keyStr).Scan(userData)
- if err != nil {
- return nil, err
- }
- return userData, nil
- }
- func DeleteUserData(userId int64) (int64, error) {
- keyStr := fmt.Sprintf("user_%d", userId)
- return Instance().Del(context.Background(), keyStr).Result()
- }
|