From e8c2b726bfa9be954fb94e7c600cd05909c0e335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=85=89=E6=98=A5?= Date: Sat, 13 Aug 2022 22:54:21 +0800 Subject: [PATCH] - update redis lock --- const.go | 2 +- redis_error.go | 8 ++------ redis_lock.go | 32 ++++++++++++++------------------ 3 files changed, 17 insertions(+), 25 deletions(-) diff --git a/const.go b/const.go index 00f4c46..0f0cc16 100644 --- a/const.go +++ b/const.go @@ -1,3 +1,3 @@ package dorm -const Version = "1.0.24" +const Version = "1.0.25" diff --git a/redis_error.go b/redis_error.go index f76df1e..548aed9 100644 --- a/redis_error.go +++ b/redis_error.go @@ -1,12 +1,8 @@ package dorm -import ( - "errors" -) - var ( // RedisNotFound 没有数据 - RedisNotFound = errors.New("redis: nil") + RedisNotFound = "redis: nil" // RedisKeysNotFound keys没有数据 - RedisKeysNotFound = errors.New("ERR wrong number of arguments for 'mget' command") + RedisKeysNotFound = "ERR wrong number of arguments for 'mget' command" ) diff --git a/redis_lock.go b/redis_lock.go index db1ccd6..352ddff 100644 --- a/redis_lock.go +++ b/redis_lock.go @@ -27,20 +27,18 @@ func (rl *RedisClientLock) Lock(ctx context.Context, key string, val string, ttl } // 获取 get, err := rl.operation.Get(ctx, key).Result() - if err != nil { - if err != RedisNotFound { - return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error())) + if err.Error() == RedisNotFound { + // 设置 + err = rl.operation.Set(ctx, key, val, ttl).Err() + if err != nil { + return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error())) } + return val, nil } if get != "" { return resp, errors.New("上锁失败,已存在") } - // 设置 - err = rl.operation.Set(ctx, key, val, ttl).Err() - if err != nil { - return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error())) - } - return val, nil + return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error())) } // Unlock 解锁 @@ -59,18 +57,16 @@ func (rl *RedisClientLock) Unlock(ctx context.Context, key string) error { func (rl *RedisClientLock) LockForever(ctx context.Context, key string, val string) (resp string, err error) { // 获取 get, err := rl.operation.Get(ctx, key).Result() - if err != nil { - if err != RedisNotFound { - return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error())) + if err.Error() == RedisNotFound { + // 设置 + err = rl.operation.Set(ctx, key, val, 0).Err() + if err != nil { + return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error())) } + return val, nil } if get != "" { return resp, errors.New("上锁失败,已存在") } - // 设置 - err = rl.operation.Set(ctx, key, val, 0).Err() - if err != nil { - return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error())) - } - return val, nil + return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error())) }