共用方式為


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();
    

注意

使用之前,別忘了啟用可設定的重試邏輯參數。 如需詳細資訊,請參閱啟用可設定的重試邏輯

另請參閱