package cache import ( "encoding/json" "git.hilo.cn/hilo-common/domain" "math/rand" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } const ( DEFAULT_TTL = time.Hour ) // 获取默认随机过期ttl func GetDefaultTTL() time.Duration { return time.Duration(rand.Intn(5))*time.Second + DEFAULT_TTL } // 设置redis json结构体 func SetJSON(model *domain.Model, key string, obj interface{}) (err error) { defer model.Log.Infof("SetJson key:%v,obj:%v,err:%v", key, obj, err) value, err := json.Marshal(obj) if err != nil { return err } return model.Redis.Set(model.Context, key, value, DEFAULT_TTL).Err() } // 获取redis中json结构体 // return err: may redisV8.Nil func GetJSON(model *domain.Model, key string, obj interface{}) (err error) { var value []byte defer func() { model.Log.Infof("GetJson key:%v,value:%s,obj:%v,err:%v", key, value, obj, err) }() value, err = model.Redis.Get(model.Context, key).Bytes() if err != nil { // may redisV2.Nil return } err = json.Unmarshal(value, &obj) if err != nil { return err } return nil } // 尝试指定时间内获取锁 // acquireTimeout: 尝试获取锁的时间 // expireTimeout: 上锁的时间 // return: true上锁成功 false失败 func TryLock(model *domain.Model, key string, acquireTimeout, expireTimeout time.Duration) bool { deadline := time.Now().Add(acquireTimeout) for { if time.Now().After(deadline) { return false } flag, err := model.Redis.SetNX(model, key, "1", expireTimeout).Result() if err != nil || !flag { time.Sleep(time.Millisecond * 10) } else { return true } } } // 解锁 func UnLock(model *domain.Model, key string) { model.Redis.Del(model, key) }