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)) {
|
||||
func Lock(ctx context.Context, key string, expireSeconds int64, fn func(ctx context.Context) error) error {
|
||||
limit := 3
|
||||
LOOP:
|
||||
if limit < 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
limit--
|
||||
if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{
|
||||
@@ -47,6 +47,7 @@ LOOP:
|
||||
NX: true,
|
||||
}); err != nil {
|
||||
glog.Errorf(ctx, "RedisClient.Lock error: %v", err)
|
||||
return nil
|
||||
} else {
|
||||
if val.Bool() {
|
||||
defer func(RedisClient *gredis.Redis, ctx context.Context, key string) {
|
||||
@@ -54,7 +55,7 @@ LOOP:
|
||||
glog.Errorf(ctx, "RedisClient.Del error: %v", err)
|
||||
}
|
||||
}(RedisClient, ctx, key)
|
||||
fn(ctx)
|
||||
return fn(ctx)
|
||||
} else {
|
||||
time.Sleep(time.Second)
|
||||
goto LOOP
|
||||
|
||||
Reference in New Issue
Block a user