SqlClient 中可配置的重试逻辑核心 API

适用于:.NET Framework .NET .NET Standard

下载 ADO.NET

如果内置的重试逻辑提供程序不能满足需求,则可以创建自己的自定义提供程序。 然后,可以将这些提供程序分配给 SqlConnectionSqlCommand 对象以应用自定义逻辑。

内置提供程序围绕三个可用于实现自定义提供程序的接口设计。 然后,可以在 SqlConnectionSqlCommand 上以与使用内部重试提供程序相同的方式来使用自定义重试提供程序:

  1. SqlRetryIntervalBaseEnumerator:生成时间间隔的序列。
  2. SqlRetryLogicBase:检索给定枚举器的下一个时间间隔(如果尚未超过重试次数,并且满足暂时性的条件)。
  3. SqlRetryLogicBaseProvider:将重试逻辑应用于连接和命令操作。

注意

通过实现自定义重试逻辑提供程序,你可以掌管所有方面,包括并发性、性能和异常管理。

示例

本示例中的实现尽可能简单,其目的是逐步演示自定义。 它不包括线程安全、异步和并发等高级做法。 若要深入了解真正的实现,可以在 Microsoft.Data.SqlClient GitHub 存储库中学习预定义的重试逻辑。

  1. 定义自定义的可配置重试逻辑类:

    • 枚举器:定义固定的时间间隔序列并将可接受的时间范围从两分钟延长到四分钟。
    public class CustomEnumerator : SqlRetryIntervalBaseEnumerator
    {
        // Set the maximum acceptable time to 4 minutes
        private readonly TimeSpan _maxValue = TimeSpan.FromMinutes(4);
    
        public CustomEnumerator(TimeSpan timeInterval, TimeSpan maxTime, TimeSpan minTime)
            : base(timeInterval, maxTime, minTime) {}
    
        // Return fixed time on each request
        protected override TimeSpan GetNextInterval()
        {
            return GapTimeInterval;
        }
    
        // Override the validate method with the new time range validation
        protected override void Validate(TimeSpan timeInterval, TimeSpan maxTimeInterval, TimeSpan minTimeInterval)
        {
            if (minTimeInterval < TimeSpan.Zero || minTimeInterval > _maxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(minTimeInterval));
            }
    
            if (maxTimeInterval < TimeSpan.Zero || maxTimeInterval > _maxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(maxTimeInterval));
            }
    
            if (timeInterval < TimeSpan.Zero || timeInterval > _maxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(timeInterval));
            }
    
            if (maxTimeInterval < minTimeInterval)
            {
                throw new ArgumentOutOfRangeException(nameof(minTimeInterval));
            }
        }
    }
    
    • 重试逻辑:对不属于活动事务的任何命令实施重试逻辑。 将重试次数从 60 降低到 20。
    public class CustomRetryLogic : SqlRetryLogicBase
    {
        // Maximum number of attempts
        private const int maxAttempts = 20;
    
        public CustomRetryLogic(int numberOfTries,
                                 SqlRetryIntervalBaseEnumerator enumerator,
                                 Predicate<Exception> transientPredicate)
        {
            if (!(numberOfTries > 0 && numberOfTries <= maxAttempts))
            {
                // 'numberOfTries' should be between 1 and 20.
                throw new ArgumentOutOfRangeException(nameof(numberOfTries));
            }
    
            // Assign parameters to the relevant properties
            NumberOfTries = numberOfTries;
            RetryIntervalEnumerator = enumerator;
            TransientPredicate = transientPredicate;
            Current = 0;
        }
    
        // Prepare this object for the next round
        public override void Reset()
        {
            Current = 0;
            RetryIntervalEnumerator.Reset();
        }
    
        public override bool TryNextInterval(out TimeSpan intervalTime)
        {
            intervalTime = TimeSpan.Zero;
            // First try has occurred before starting the retry process. 
            // Check if retry is still allowed
            bool result = Current < NumberOfTries - 1;
    
            if (result)
            {
                // Increase the number of attempts
                Current++;
                // It's okay if the RetryIntervalEnumerator gets to the last value before we've reached our maximum number of attempts.
                // MoveNext() will simply leave the enumerator on the final interval value and we will repeat that for the final attempts.
                RetryIntervalEnumerator.MoveNext();
                // Receive the current time from enumerator
                intervalTime = RetryIntervalEnumerator.Current;
            }
            return result;
        }
    }
    
    • 提供程序:在没有 Retrying 事件的情况下,实现对同步操作的进行重试的重试提供程序。 将 TimeoutException 添加到现有 SqlException 暂时性异常错误编号。
    public class CustomProvider : SqlRetryLogicBaseProvider
    {
        // Preserve the given retryLogic on creation
        public CustomProvider(SqlRetryLogicBase retryLogic)
        {
            RetryLogic = retryLogic;
        }
    
        public override TResult Execute<TResult>(object sender, Func<TResult> function)
        {
            // Create a list to save transient exceptions to report later if necessary
            IList<Exception> exceptions = new List<Exception>();
            // Prepare it before reusing
            RetryLogic.Reset();
            // Create an infinite loop to attempt the defined maximum number of tries
            do
            {
                try
                {
                    // Try to invoke the function
                    return function.Invoke();
                }
                // Catch any type of exception for further investigation
                catch (Exception e)
                {
                    // Ask the RetryLogic object if this exception is a transient error
                    if (RetryLogic.TransientPredicate(e))
                    {
                        // Add the exception to the list of exceptions we've retried on
                        exceptions.Add(e);
                        // Ask the RetryLogic for the next delay time before the next attempt to run the function
                        if (RetryLogic.TryNextInterval(out TimeSpan gapTime))
                        {
                            Console.WriteLine($"Wait for {gapTime} before next try");
                            // Wait before next attempt
                            Thread.Sleep(gapTime);
                        }
                        else
                        {
                            // Number of attempts has exceeded the maximum number of tries
                            throw new AggregateException("The number of retries has exceeded the maximum number of attempts.", exceptions);
                        }
                    }
                    else
                    {
                        // If the exception wasn't a transient failure throw the original exception
                        throw;
                    }
                }
            } while (true);
        }
    
        public override Task<TResult> ExecuteAsync<TResult>(object sender, Func<Task<TResult>> function, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    
        public override Task ExecuteAsync(object sender, Func<Task> function, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }
    }
    
  2. 创建由定义的自定义类型组成的重试提供程序实例:

    public static SqlRetryLogicBaseProvider CreateCustomProvider(SqlRetryLogicOption options)
    {
        // 1. create an enumerator instance
        CustomEnumerator customEnumerator = new CustomEnumerator(options.DeltaTime, options.MaxTimeInterval, options.MinTimeInterval);
        // 2. Use the enumerator object to create a new RetryLogic instance
        CustomRetryLogic customRetryLogic = new CustomRetryLogic(5, customEnumerator, (e) => TransientErrorsCondition(e, options.TransientErrors));
        // 3. Create a provider using the RetryLogic object
        CustomProvider customProvider = new CustomProvider(customRetryLogic);
        return customProvider;
    }
    
    • 以下函数将使用给定的可重试异常列表和特殊的 TimeoutException 异常来评估异常,从而确定是否可重试:
    // Return true if the exception is a transient fault.
    private static bool TransientErrorsCondition(Exception e, IEnumerable<int> retriableConditions)
    {
        bool result = false;
    
        // Assess only SqlExceptions
        if (retriableConditions != null && e is SqlException ex)
        {
            foreach (SqlError item in ex.Errors)
            {
                // Check each error number to see if it is a retriable error number
                if (retriableConditions.Contains(item.Number))
                {
                    result = true;
                    break;
                }
            }
        }
        // Other types of exceptions can also be assessed
        else if (e is TimeoutException)
        {
            result = true;
        }
        return result;
    }
    
  3. 使用自定义重试逻辑:

    • 定义重试逻辑参数:
    // Define the retry logic parameters
    var options = new SqlRetryLogicOption()
    {
        // Tries 5 times before throwing an exception
        NumberOfTries = 5,
        // Preferred gap time to delay before retry
        DeltaTime = TimeSpan.FromSeconds(1),
        // Maximum gap time for each delay time before retry
        MaxTimeInterval = TimeSpan.FromSeconds(20),
        // SqlException retriable error numbers
        TransientErrors = new int[] { 4060, 1024, 1025}
    };
    
    • 创建自定义重试提供程序:
    // Create a custom retry logic provider
    SqlRetryLogicBaseProvider provider = CustomRetry.CreateCustomProvider(options);
    
    // Assumes that connection is a valid SqlConnection object 
    // Set the retry logic provider on the connection instance
    connection.RetryLogicProvider = provider;
    // Establishing the connection will trigger retry if one of the given transient failure occurs.
    connection.Open();
    

注意

请不要忘记启用可配置的重试逻辑开关,然后再使用它。 有关详细信息,请参阅启用可配置的重试逻辑

另请参阅