适用于: .NET Framework
.NET
.NET Standard
本文展示了如何创建一个指数重试提供者并将其分配给一个 SqlConnection。 服务提供商会重试驱动程序内置的瞬态连接错误列表,并尝试最多开启连接五次。
先决条件
- Microsoft。Data.SqlClient 3.0 或更高版本。
- 用于 SQL Server、Azure SQL 数据库、Azure SQL 托管实例 或 Microsoft Fabric 中 SQL 数据库的连接字符串。
配置连接重试提供者
定义重试选项。 将 保留为
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) };从选项中创建一个服务提供者。
// Create a retry logic provider SqlRetryLogicBaseProvider provider = SqlConfigurableRetryFactory.CreateExponentialRetryProvider(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 retry if a transient failure occurs. connection.Open();
NumberOfTries = 5 允许一次初次尝试,最多可重复四次。 指数供应器会延长尝试间隔并增加随机抖动。
MaxTimeInterval 限制每个具体延迟,而不是所有尝试的总耗时。
配置命令重试机制
创建一个独立的提供者并分配给 SqlCommand.RetryLogicProvider。 将SqlRetryLogicOption.AuthorizedSqlCondition设置为一个仅对应用程序可安全重复执行的命令返回true的谓词。
Caution
内置的提供者不会在连接有活跃事务时重试命令。 如果瞬时故障导致事务失效,请回滚并重试整个事务。 不要只重试失败的语句。
设置 SqlRetryLogicOption.TransientErrors 替换了驱动内置的错误列表。 如需扩展基线而不丢失默认值,请参见 “扩展内置瞬态错误列表”。