package redis import ( "context" "fmt" "time" "git.x2erp.com/qdy/go-base/config" "git.x2erp.com/qdy/go-base/config/subconfigs" "github.com/go-redis/redis/v8" ) var ctxRedis = context.Background() // RedisFactory Redis客户端工厂 type RedisFactory struct { redisConfig *subconfigs.RedisConfig } // NewRedisFactory 创建Redis客户端工厂 func NewRedisFactory() (*RedisFactory, error) { cfg := config.GetRedisConfig() // 可以添加配置验证 if cfg == nil || cfg.Host == "" { return nil, fmt.Errorf("redis configuration is incomplete") } return &RedisFactory{redisConfig: cfg}, nil } // CreateRedisClient 创建Redis客户端 func (f *RedisFactory) CreateRedisClient() *RedisClient { redisConfig := f.redisConfig client := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port), Password: redisConfig.Password, DB: redisConfig.DB, PoolSize: redisConfig.PoolSize, }) return &RedisClient{ client: client, } } // RedisClient Redis客户端 type RedisClient struct { client *redis.Client } // Set 写入字符串值 func (c *RedisClient) Set(key string, value interface{}, expiration time.Duration) error { return c.client.Set(ctxRedis, key, value, expiration).Err() } // Get 读取字符串值 func (c *RedisClient) Get(key string) (string, error) { return c.client.Get(ctxRedis, key).Result() } // HSet 写入哈希字段 func (c *RedisClient) HSet(key string, values ...interface{}) error { return c.client.HSet(ctxRedis, key, values...).Err() } // HGet 读取哈希字段 func (c *RedisClient) HGet(key, field string) (string, error) { return c.client.HGet(ctxRedis, key, field).Result() } // HGetAll 读取整个哈希 func (c *RedisClient) HGetAll(key string) (map[string]string, error) { return c.client.HGetAll(ctxRedis, key).Result() } // LPush 列表左推入 func (c *RedisClient) LPush(key string, values ...interface{}) error { return c.client.LPush(ctxRedis, key, values...).Err() } // RPop 列表右弹出 func (c *RedisClient) RPop(key string) (string, error) { return c.client.RPop(ctxRedis, key).Result() } // Del 删除键 func (c *RedisClient) Del(keys ...string) error { return c.client.Del(ctxRedis, keys...).Err() } // Exists 检查键是否存在 func (c *RedisClient) Exists(keys ...string) (int64, error) { return c.client.Exists(ctxRedis, keys...).Result() } // Close 关闭连接 func (c *RedisClient) Close() error { return c.client.Close() }