refactor: 将分布式锁从 redis 迁移至 utils 包
This commit is contained in:
@@ -2,7 +2,6 @@ package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -38,40 +37,6 @@ func RedisClient() *gredis.Redis {
|
||||
return getClient()
|
||||
}
|
||||
|
||||
// Lock 分布式锁
|
||||
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 false, errors.New("锁重试次数耗尽")
|
||||
}
|
||||
limit--
|
||||
client := getClient()
|
||||
if val, err := client.Set(ctx, key, true, gredis.SetOption{
|
||||
TTLOption: gredis.TTLOption{
|
||||
EX: &expireSeconds,
|
||||
},
|
||||
NX: true,
|
||||
}); err != nil {
|
||||
return false, err
|
||||
} else {
|
||||
if val.Bool() {
|
||||
defer func(client *gredis.Redis, ctx context.Context, key string) {
|
||||
if _, err = client.Del(ctx, key); err != nil {
|
||||
glog.Errorf(ctx, "redis client Del error: %v", err)
|
||||
}
|
||||
}(client, ctx, key)
|
||||
if err = fn(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
} else {
|
||||
time.Sleep(time.Second)
|
||||
goto LOOP
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetReadStream(ctx context.Context, msg ...QueueMessage) error {
|
||||
for _, t := range msg {
|
||||
err := GetReadFromStream(ctx, t.StreamKey, t.GroupName, t.ConsumerName, t.BatchSize, t.BlockMs, t.AutoAck, t.HandleFunc)
|
||||
|
||||
Reference in New Issue
Block a user