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