modelRedis.go 1.66 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
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)
}