common/redis增加Lock方法,
This commit is contained in:
@@ -33,11 +33,11 @@ func GetRedisClient() *gredis.Redis {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Lock 分布式锁
|
// Lock 分布式锁
|
||||||
func Lock(ctx context.Context, key string, expireSeconds int64, fn func(ctx context.Context) error) error {
|
func Lock(ctx context.Context, key string, expireSeconds int64, fn func(ctx context.Context) error) (success bool, err error) {
|
||||||
limit := 3
|
limit := 3
|
||||||
LOOP:
|
LOOP:
|
||||||
if limit < 0 {
|
if limit < 0 {
|
||||||
return nil
|
return
|
||||||
}
|
}
|
||||||
limit--
|
limit--
|
||||||
if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{
|
if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{
|
||||||
@@ -46,8 +46,7 @@ LOOP:
|
|||||||
},
|
},
|
||||||
NX: true,
|
NX: true,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
glog.Errorf(ctx, "RedisClient.Lock error: %v", err)
|
return
|
||||||
return nil
|
|
||||||
} else {
|
} else {
|
||||||
if val.Bool() {
|
if val.Bool() {
|
||||||
defer func(RedisClient *gredis.Redis, ctx context.Context, key string) {
|
defer func(RedisClient *gredis.Redis, ctx context.Context, key string) {
|
||||||
@@ -55,7 +54,10 @@ LOOP:
|
|||||||
glog.Errorf(ctx, "RedisClient.Del error: %v", err)
|
glog.Errorf(ctx, "RedisClient.Del error: %v", err)
|
||||||
}
|
}
|
||||||
}(RedisClient, ctx, key)
|
}(RedisClient, ctx, key)
|
||||||
return fn(ctx)
|
if err = fn(ctx); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
} else {
|
} else {
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
goto LOOP
|
goto LOOP
|
||||||
|
|||||||
Reference in New Issue
Block a user