common/redis增加Lock方法,

This commit is contained in:
2025-12-26 17:35:52 +08:00
parent a464e4187a
commit 6c9e8b125a

View File

@@ -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