first commit
This commit is contained in:
68
pkg/cache/redis_lock.go
vendored
Normal file
68
pkg/cache/redis_lock.go
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"servicebase/pkg/log"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Lock(key string) (e error) {
|
||||
var success bool
|
||||
TryMax := 6
|
||||
redisClient := GetCommonRedisInstance().RedisClient
|
||||
for i := 0; i < TryMax; i++ {
|
||||
success, e = redisClient.SetNX(Ctx(), key, time.Now(), time.Millisecond*1000*3).Result()
|
||||
if e != nil {
|
||||
log.Info("Lock GetCommonRedisInstance error: " + e.Error())
|
||||
}
|
||||
if success {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(time.Millisecond * 50)
|
||||
}
|
||||
return errors.New("操作太频繁了~")
|
||||
}
|
||||
|
||||
func Free(key string) {
|
||||
client := GetCommonRedisInstance().RedisClient
|
||||
_ = client.Del(Ctx(), key).Err()
|
||||
}
|
||||
|
||||
const (
|
||||
TryMax = int(30)
|
||||
TryDuration = time.Millisecond * 13
|
||||
LockTimeout = time.Millisecond * 700
|
||||
)
|
||||
|
||||
func RedisLockGetTime(key string, duration time.Duration) (e error) {
|
||||
redisClient := GetCommonRedisInstance().RedisClient
|
||||
success, e := redisClient.SetNX(Ctx(), key, "1", duration).Result()
|
||||
if !success {
|
||||
e = errors.New("(LOCK_FAILED)系统繁忙,请稍后再试!")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func RedisLockGet(key string) (e error) {
|
||||
redisClient := GetCommonRedisInstance().RedisClient
|
||||
success := false
|
||||
for i := 0; i < TryMax; i++ {
|
||||
success, e = redisClient.SetNX(Ctx(), key, time.Now(), LockTimeout).Result()
|
||||
if nil != e {
|
||||
return
|
||||
}
|
||||
if success {
|
||||
break
|
||||
}
|
||||
time.Sleep(TryDuration)
|
||||
}
|
||||
if !success {
|
||||
e = errors.New("(LOCK_FAILED)系统繁忙,请稍后再试!")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func RedisLockDel(key string) {
|
||||
redisClient := GetCommonRedisInstance().RedisClient
|
||||
_ = redisClient.Del(Ctx(), key).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user