fix Delay

This commit is contained in:
liangzai 2025-03-21 16:18:58 +08:00
parent 29f248f1b4
commit 9059458433

View File

@ -900,24 +900,8 @@ func (a *ApiRequestService) ProcessCAR059Request(ctx context.Context, params []b
maxRetries, orderID.String()) maxRetries, orderID.String())
} }
// 计算基础延迟时间 // 固定延迟时间为15秒
var delay time.Duration fixedDelay := 15 * time.Second
if retryCount == 0 {
delay = 10 * time.Millisecond // 第一次设置极小延迟而非0
} else {
// 指数退避策略
baseDelay := 3 * time.Second
maxDelay := 1 * time.Hour
delay = baseDelay
for i := 1; i < int(retryCount); i++ {
delay = delay * 2
if delay > maxDelay {
delay = maxDelay
break
}
}
}
// 检查ctx是否已经有超时 // 检查ctx是否已经有超时
deadline, hasDeadline := ctx.Deadline() deadline, hasDeadline := ctx.Deadline()
@ -929,32 +913,20 @@ func (a *ApiRequestService) ProcessCAR059Request(ctx context.Context, params []b
return nil, fmt.Errorf("上下文已超时,停止重试,订单号: %s", orderID.String()) return nil, fmt.Errorf("上下文已超时,停止重试,订单号: %s", orderID.String())
} }
// 保留一些安全边界,确保有足够时间执行后续操作 // 如果剩余时间不足以等待完整的15秒
safetyBuffer := 500 * time.Millisecond if timeRemaining < fixedDelay+500*time.Millisecond {
logx.Infof("上下文剩余时间不足,提前返回,订单号: %s, 剩余时间: %v",
// 如果剩余时间不足以完成当前延迟加安全边界 orderID.String(), timeRemaining)
if timeRemaining < delay+safetyBuffer { return nil, fmt.Errorf("上下文剩余时间不足,无法完成下一次重试")
// 使用剩余时间的50%作为延迟,确保有足够时间完成后续操作
adjustedDelay := time.Duration(float64(timeRemaining) * 0.5)
// 确保最小延迟不小于10毫秒
if adjustedDelay < 10*time.Millisecond {
adjustedDelay = 10 * time.Millisecond
}
logx.Infof("调整延迟时间以适应上下文超时,原始延迟: %v, 新延迟: %v, 剩余时间: %v",
delay, adjustedDelay, timeRemaining)
delay = adjustedDelay
} }
} }
// 等待指定延迟时间 // 等待固定的延迟时间
logx.Infof("安排延迟重试,订单号: %s, 延迟: %v, 重试次数: %d", logx.Infof("安排固定延迟重试,订单号: %s, 延迟: 15秒, 重试次数: %d",
orderID.String(), delay, retryCount+1) orderID.String(), retryCount+1)
select { select {
case <-time.After(delay): case <-time.After(fixedDelay):
// 延迟时间到,继续处理 // 延迟时间到,继续处理
case <-ctx.Done(): case <-ctx.Done():
// 上下文被取消,返回错误 // 上下文被取消,返回错误