util.go 1.58 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
package redisCli

import (
	"context"
	"hilo-socketCenter/common/mylogrus"
	"strconv"
	"time"
)

//这个用户避免多个服务器并发问题。
func SetNX(key string, value interface{}, expiration time.Duration, callBack func()) {
	flag, err := RedisClient.SetNX(context.Background(), key, value, expiration).Result()
	if err != nil {
		mylogrus.MyLog.Errorf("key:%v lock start setNx err: %v", key, err)
	}
	if !flag {
		mylogrus.MyLog.Infof("key:%v lock setNx has lock", key)
		return
	}
	mylogrus.MyLog.Infof("key:%v lock setNx begin", key)
	callBack()
	//执行结束之后,移除key
	//RedisClient.Del(context.Background(), key)
	mylogrus.MyLog.Infof("key:%v lock setNx end", key)
}

//setNx没有,结束后,没有移除
/*func SetNxNoDel(key string, value interface{}, expiration time.Duration, callBack func()) {
	flag, err := RedisClient.SetNX(context.Background(), key, value, expiration).Result()
	if err != nil {
		mylogrus.MyLog.Errorf("key:%v lock start setNx err: %v", key, err)
	}
	if !flag {
		mylogrus.MyLog.Infof("key:%v lock setNx has lock", key)
		return
	}
	mylogrus.MyLog.Infof("key:%v lock setNx begin", key)
	callBack()
	mylogrus.MyLog.Infof("key:%v lock setNx end", key)
}*/

func ClearExpired(key string, expireSec int64) error {
	return GetRedis().ZRemRangeByScore(context.Background(), key,
		"0", strconv.FormatInt(time.Now().Unix()-expireSec, 10)).Err()
}

func Lock(key string, expiration time.Duration) bool {
	flag, err := RedisClient.SetNX(context.Background(), key, 1, expiration).Result()
	if err != nil {
		return false
	}
	if !flag {
		return false
	}
	return true
}