package redis import ( "context" "encoding/json" "github.com/panjf2000/gnet/v2/pkg/logging" "github.com/redis/go-redis/v9" "time" ) var cacheInstance *CacheClient type CacheClient struct { cli *redis.Client logger logging.Logger } func GetCacheClient() *CacheClient { return cacheInstance } func (c *CacheClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) { bytes, err := json.Marshal(value) if err != nil { c.logger.Errorf("Set json.Marshal error: %v, key: %v, value: %v", err, key, value) return } if err = c.cli.Set(ctx, key, bytes, expiration).Err(); err != nil { c.logger.Errorf("Set redis.Set error: %v, key: %v, value: %v", err, key, value) } } func (c *CacheClient) Del(ctx context.Context, keys ...string) { if err := c.cli.Del(ctx, keys...).Err(); err != nil { c.logger.Errorf("Set redis.Del error: %v, keys: %v", err, keys) } } // Get 获取数据 func (c *CacheClient) Get(ctx context.Context, key string, dst interface{}) bool { data, err := c.cli.Get(ctx, key).Bytes() if err != nil { return false } if err = json.Unmarshal(data, dst); err != nil { c.logger.Errorf("Get json.Unmarshal error: %v, key: %v", err, key) return false } return true }