更新redis重试三次,http方法兼容ragflow格式

This commit is contained in:
Cold
2026-01-13 17:44:14 +08:00
committed by 张斌
parent aa3063c1de
commit 1fe3f127c3
3 changed files with 34 additions and 59 deletions

View File

@@ -2,7 +2,6 @@ package redis
import (
"context"
"errors"
"strings"
"sync"
"time"
@@ -15,60 +14,27 @@ import (
)
var (
// redisClient 内部使用的 Redis 客户端(单例模式)
redisClient *gredis.Redis
redisOnce sync.Once
)
// getClient 获取 Redis 客户端(延迟初始化
func getClient() *gredis.Redis {
// RedisClient 获取Redis客户端支持重试3次每次间隔2秒
func RedisClient() *gredis.Redis {
redisOnce.Do(func() {
redisClient = g.Redis()
for i := 0; i < 3; i++ {
redisClient = g.Redis()
if redisClient != nil {
ctx := context.Background()
if _, err := redisClient.Do(ctx, "PING"); err == nil {
return
}
}
time.Sleep(2 * time.Second)
}
})
return redisClient
}
// GetRedisClient 获取 Redis 客户端(供外部使用)
func GetRedisClient() *gredis.Redis {
return getClient()
}
// RedisClient 导出的 Redis 客户端(供 mongo.go 使用,兼容旧代码)
var RedisClient = 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--
if val, err := RedisClient.Set(ctx, key, true, gredis.SetOption{
TTLOption: gredis.TTLOption{
EX: &expireSeconds,
},
NX: true,
}); err != nil {
return false, err
} else {
if val.Bool() {
defer func(RedisClient *gredis.Redis, ctx context.Context, key string) {
if _, err = RedisClient.Del(ctx, key); err != nil {
glog.Errorf(ctx, "RedisClient.Del error: %v", err)
}
}(RedisClient, 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)