first commit

This commit is contained in:
Yangtao
2025-11-18 17:48:20 +08:00
commit 6e56cab848
196 changed files with 65809 additions and 0 deletions

68
pkg/cache/redis_lock.go vendored Normal file
View 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()
}