在 SqlClient 中設定重試邏輯

適用於: .NET Framework .NET .NET 標準

下載 ADO.NET

本文說明如何建立指數重試提供者並將其指派給 SqlConnection。 提供者會重試驅動程式內建的暫時性連線錯誤清單,並嘗試最多五次開啟連線。

先決條件

  • Microsoft。Data.SqlClient 3.0 或更新版本。
  • 適用於 SQL Server、Azure SQL Database、Azure SQL 受控執行個體 或 Microsoft Fabric 中 SQL 資料庫的連線字串。

設定連線重試提供者

  1. 定義重試選項。 將 保持為 TransientErrors,使提供者使用 null。

    // 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)
    };
    
  2. 從選項中建立一個提供者。

    // Create a retry logic provider
    SqlRetryLogicBaseProvider provider = SqlConfigurableRetryFactory.CreateExponentialRetryProvider(options);
    
  3. 在開啟連線前先指派服務提供者。

    // Assumes that connection is a valid SqlConnection object 
    // Set the retry logic provider on the connection instance
    connection.RetryLogicProvider = provider;
    // Establishing the connection will retry if a transient failure occurs.
    connection.Open();
    

NumberOfTries = 5 允許一次初次嘗試,最多可重試四次。 指數供應者會增加嘗試間隔並增加隨機抖動。 MaxTimeInterval 針對每次延遲設上限,而非針對所有嘗試的總耗時。

設定指令重試

建立一個獨立的提供者並指派給 SqlCommand.RetryLogicProvider。 將 SqlRetryLogicOption.AuthorizedSqlCondition 設定為僅對您的應用程式可安全重複執行的命令回傳 true 的述詞。

注意事項

內建的提供者不會在連線有活躍交易時重試指令。 如果暫時性故障導致交易失效,請回滾並重新嘗試整個交易。 不要只重試失敗的陳述式。

設定 SqlRetryLogicOption.TransientErrors 會取代驅動程式內建的錯誤清單。 若要擴展基線而不失去預設值,請參見 「延伸內建暫態錯誤清單」。