common/redis增加Lock方法,

This commit is contained in:
2025-12-26 17:18:31 +08:00
parent c4b4cfe50f
commit a464e4187a

View File

@@ -33,11 +33,11 @@ func GetRedisClient() *gredis.Redis {
} }
// Lock 分布式锁 // 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 limit := 3
LOOP: LOOP:
if limit < 0 { if limit < 0 {
return return nil
} }
limit-- limit--
if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{ if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{
@@ -47,6 +47,7 @@ LOOP:
NX: true, NX: true,
}); err != nil { }); err != nil {
glog.Errorf(ctx, "RedisClient.Lock error: %v", err) glog.Errorf(ctx, "RedisClient.Lock error: %v", err)
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) {
@@ -54,7 +55,7 @@ LOOP:
glog.Errorf(ctx, "RedisClient.Del error: %v", err) glog.Errorf(ctx, "RedisClient.Del error: %v", err)
} }
}(RedisClient, ctx, key) }(RedisClient, ctx, key)
fn(ctx) return fn(ctx)
} else { } else {
time.Sleep(time.Second) time.Sleep(time.Second)
goto LOOP goto LOOP