xredis库操作丰富

配置:

{
    "redis2_dsn":{
        "dsn": "redis://:@172.16.1.222:6379/0",
        "maxActive": 200,
        "maxIdle": 2,
        "timeoutSec": 1
    }
}

检查更新代码:

func GetRedis(key string) *Redis {
    mu.RLock()
    conf := getRedisConf(key)
    if redisMap[key] != nil {
        defer mu.RUnlock()
        checkConfigUpate(key, conf)
        return redisMap[key]
    }
    mu.RUnlock()
    mu.Lock()
    defer mu.Unlock()

    initRedis(key)
    return redisMap[key]
}

func checkConfigUpate(key string, conf *RedisConf) {
    objRedis := redisMap[key]
    if objRedis.redisConf.Dsn != conf.Dsn {
        // 链接不一样,需要重新初始化
        objRedis2 := newRedis2(conf)
        redisMap[key] = objRedis2
        xlog.Warn2("redis dsn change, key:" + key + " old:",  objRedis.redisConf.Dsn, ", new:", conf.Dsn)
        // 关闭老链接
        err := objRedis.Close()
        xlog.Warn2("redis close old dsn:",  objRedis.redisConf.Dsn, ", err:", err)
    }

    if objRedis.redisConf.MaxIdle != conf.MaxIdle {
        xlog.Warn2("redis MaxIdle change, key:" + key + " old:",  objRedis.redisConf.MaxIdle, ", new:", conf.MaxIdle)
        objRedis.pool.MaxIdle = int(conf.MaxIdle)
        objRedis.redisConf.MaxIdle = conf.MaxIdle
    }

    if objRedis.redisConf.MaxActive != conf.MaxActive {
        xlog.Warn2("redis MaxActive change, key:" + key + " old:",  objRedis.redisConf.MaxActive, ", new:", conf.MaxActive)
        objRedis.pool.MaxActive = int(conf.MaxActive)
        objRedis.redisConf.MaxActive = conf.MaxActive
    }

    if objRedis.redisConf.TimeoutSec != conf.TimeoutSec {
        xlog.Warn2("redis TimeoutSec change, key:" + key + " old:",  objRedis.redisConf.TimeoutSec, ", new:", conf.TimeoutSec)
        objRedis.redisConf.TimeoutSec = conf.TimeoutSec
    }
}

完善各种操作

image-20200713202337295

设计原则

o := GetRedis(redisKey)
// 明确类型的操作,直接返回对应类型
var flag bool = o.Exists(ctx, "bool_key")  // bool类型
var incrVal int64 = o.Incr(ctx, "int64_key") // int64类型
var hashLen int64 = o.HLen(ctx, "hash_key") // int64类型
...

// 不明确的类型,返回 *redisResult

// 单元素
ret, isNil := o.Get(ctx, "key").String() // string类型
ret, isNil := o.Get(ctx, "key").Int()  // int类型
ret, isNil := o.Get(ctx, "key").Int64()  // int64类型
...

// 数组,或map类型
mapRet, isNil := o.HGetAll(ctx, key).StringMap()  // map[string]string
mapRet, isNil := o.HGetAll(ctx, key).Int64Map()  // map[string]int64
mapRet, isNil := o.MGet(ctx, "key1", "key2").Strings()  // []string
...

精细控制,例如:timeout、error,则使用:

func (r *Redis) Do(ctx context.Context, cmd string, args ...interface{}) (reply interface{}, err error)
func (r *Redis) DoWithTimeout(ctx context.Context, timeout time.Duration, cmd string, args ...interface{}) (reply interface{}, err error)
Copyright © xinyan all right reserved,powered by Gitbook该文件修订时间: 2020-07-29 10:10:38

results matching ""

    No results matching ""