package redis import ( "context" "encoding/json" "log" "runtime" "strings" "time" "github.com/go-redis/redis/v8" ) //"other=127.0.0.1:2203,push=127.0.0.1:2203,sso=172.17.4.83:1711" //"other=127.0.0.1:2203=0,push=127.0.0.1:2203,sso=172.17.4.83:1711" var ( ctx = context.Background() RedisPool map[string]*redis.Client ) type RedisUtil interface { Init(opt interface{}) Put(key string, val interface{}) //单个存放 // Get(key string) //单个获取 // GetByPattern(key string) //根据正则获取 // BulkPut(timeout int, obj ...interface{}) //批量存储 // BulkGet(key ...string) //批量获取 // Expire(key string, expire int) //设置过期 // Exists(key string) //是否存在 // FlushDB(dbnum ...int) //清空 // Del(key ...interface{}) //删除key // DelByPattern(key ...string) //根据正则删除 // Incr(key string) //自增 // Decr(key string, val int) //自减 // Pop(key string) //移除并获取某个key // LPOP(list string) //移出并获取列表的第一个元素 // RPUSH(list string, val interface{}) //在列表中添加一个或多个值 // LLEN(list string) //获取列表长度 } func InitRedis(addrs string) { InitRedisBySize(addrs, 80, 10, 240) } func InitRedisBySize(addrs string, maxSize, maxIdle, timeout int) { RedisPool = map[string]*redis.Client{} addr := strings.Split(addrs, ",") for _, v := range addr { saddr := strings.Split(v, "=") RedisPool[saddr[0]] = redis.NewClient(&redis.Options{ Addr: saddr[1], Password: "", DB: 0, PoolSize: maxSize, MinIdleConns: maxIdle, IdleTimeout: time.Duration(timeout) * time.Second, }) } } //并存入字符串缓存 func PutKV(key string, obj interface{}) bool { return Put("other", key, obj, -1) } func PutCKV(code, key string, obj interface{}) bool { return Put(code, key, obj, -1) } func Put(code, key string, obj interface{}, timeout int) bool { b := false defer catch() var err error _obj, _err := json.Marshal(obj) if _err != nil { log.Println("redisutil-SET-序列化出错Error", _err) return b } if timeout < 1 { _, err = RedisPool[code].Set(ctx, key, _obj, 0).Result() } else { _, err = RedisPool[code].SetEX(ctx, key, _obj, time.Duration(timeout)*time.Second).Result() } if nil != err { log.Println("redisutil-SETError-put", err) } else { b = true } return b } func catch() { if r := recover(); r != nil { log.Println(r) for skip := 0; ; skip++ { _, file, line, ok := runtime.Caller(skip) if !ok { break } go log.Printf("%v,%v\n", file, line) } } }