– 配置文件结构体
type ConfigLite struct {
Addr []string `toml:"addr"` //redis地址因为需要考虑单机版和集成的情况下 地址使用[]string
Password string `toml:"password"` //密码 没有则为空
DB int `toml:"db"` //使用的数据库
MasterName string `toml:"master_name"` //有值则为哨兵模式
DialConnectionTimeout time.Duration `toml:"dial_connection_timeout"`
DialReadTimeout time.Duration `toml:"dial_read_timeout"`
DialWriteTimeout time.Duration `toml:"dial_write_timeout"`
IdleTimeout time.Duration `toml:"idle_timeout"`
}
– 连接Redis
func MustBootUp(config ConfigLite) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
c := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: config.Addr,
DB: config.DB,
Password: config.Password,
MasterName: config.MasterName,
DialTimeout: time.Second * config.DialConnectionTimeout,
ReadTimeout: time.Second * config.DialReadTimeout,
WriteTimeout: time.Second * config.DialWriteTimeout,
IdleTimeout: time.Second * config.IdleTimeout,
})
_, err := c.Ping(ctx).Result()
if err != nil {
return err
}
return nil
}
客户端连接成功后,其他操作并没有什么变化,通用客户端主要是为了切换redis模式
连接redis
func GetClient(name string) (redis.UniversalClient, error) {
p, ok := redisMgr[name]
if !ok {
return nil, fmt.Errorf("redis instance not found[%s]", name)
}
return p, nil
}
redis排行榜
// DepositZIncrBy 写入排行榜
func DepositZIncrBy(key string, z redis.Z) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
redisClient, err := GetClient(constant.RedisName)//redis 名称 在配置文件里设置
if err != nil {
return err
}
_, err = redisClient.ZIncrBy(ctx, key, z.Score, z.Member.(string)).Result()
if err != nil {
zap.L().Error("Leaderboard storage error", zap.Error(err))
return err
}
return nil
}
// GetDepositByRedis 查询排行榜
func GetDepositByRedis(key string, start, stop int64) ([]redis.Z, error) {
//start 开始位置
//stop 结束位置
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
redisClient, err := GetClient(constant.RedisName)
if err != nil {
return nil, err
}
ret, err := redisClient.ZRevRangeWithScores(ctx, key, start, stop).Result()
if err != nil {
return nil, err
}
return ret, nil
}
redis 删除
// DelRedisByKeys 删除redis 可同时删除多个key
func DelRedisByKeys(key ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
redisClient, err := GetClient(constant.RedisName)
if err != nil {
return err
}
_, err = redisClient.Del(ctx, key...).Result()
if err != nil {
return err
}
return nil
}