modelRedis.go 1.69 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
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
	}
hujiebin's avatar
hujiebin committed
30
	return model.RedisCluster.Set(model.Context, key, value, DEFAULT_TTL).Err()
hujiebin's avatar
hujiebin committed
31 32 33 34 35 36
}

// 获取redis中json结构体
// return err: may redisV8.Nil
func GetJSON(model *domain.Model, key string, obj interface{}) (err error) {
	var value []byte
iamhujiebin's avatar
iamhujiebin committed
37 38 39
	//defer func() {
	//	model.Log.Infof("GetJson key:%v,value:%s,obj:%v,err:%v", key, value, obj, err)
	//}()
hujiebin's avatar
hujiebin committed
40
	value, err = model.RedisCluster.Get(model.Context, key).Bytes()
hujiebin's avatar
hujiebin committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	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
		}
hujiebin's avatar
hujiebin committed
62
		flag, err := model.RedisCluster.SetNX(model, key, "1", expireTimeout).Result()
hujiebin's avatar
hujiebin committed
63 64 65 66 67 68 69 70 71 72
		if err != nil || !flag {
			time.Sleep(time.Millisecond * 10)
		} else {
			return true
		}
	}
}

// 解锁
func UnLock(model *domain.Model, key string) {
hujiebin's avatar
hujiebin committed
73
	model.RedisCluster.Del(model, key)
hujiebin's avatar
hujiebin committed
74
}