package cache import ( "errors" "time" "gitea.ddegame.cn/open/servicebase/pkg/log" ) func Lock(key string) (e error) { var success bool TryMax := 6 redisClient := GetCommonRedisInstance().RedisClient for range TryMax { 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 range TryMax { 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() }