【发布时间】:2017-10-03 01:07:10
【问题描述】:
是否有任何 ASP.NET 包/DLL 允许 MySQL 查询执行在失败时重试?
我已经阅读了Transient Fault Handling 甚至遇到了Dapper issue which shows an example,但根据我的研究,这仅适用于 SqlServer 和/或 Azure。
我的技术栈如下:
- .NET 4.5.2
- 小巧玲珑 1.50.2.0
- MySQL 5.6(使用 Amazon Aurora)
最终我正在尝试解决sporadic failure issue,我相信实施一些重试逻辑将有助于缓解问题。
我尝试从 Dapper issue 实现一些代码,但因为我使用 MySql.Data 连接到我的 MySql 数据库,它不适用于特定于 SqlServer 连接的各种方法。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
namespace TransientDapper
{
public static class TransientDapperExtensions
{
private static readonly RetryManager SqlRetryManager = GetDefaultRetryManager();
private static readonly RetryPolicy SqlCommandRetryPolicy = SqlRetryManager.GetDefaultSqlCommandRetryPolicy();
private static readonly RetryPolicy SqlConnectionRetryPolicy =
SqlRetryManager.GetDefaultSqlConnectionRetryPolicy();
private static RetryManager GetDefaultRetryManager()
{
const int retryCount = 4;
const int minBackoffDelayMilliseconds = 2000;
const int maxBackoffDelayMilliseconds = 8000;
const int deltaBackoffMilliseconds = 2000;
var exponentialBackoffStrategy =
new ExponentialBackoff(
"exponentialBackoffStrategy",
retryCount,
TimeSpan.FromMilliseconds(minBackoffDelayMilliseconds),
TimeSpan.FromMilliseconds(maxBackoffDelayMilliseconds),
TimeSpan.FromMilliseconds(deltaBackoffMilliseconds)
);
var manager = new RetryManager(
new List<RetryStrategy>
{
exponentialBackoffStrategy
},
exponentialBackoffStrategy.Name
);
return manager;
}
public static void OpenWithRetry(this SqlConnection cnn)
{
cnn.OpenWithRetry(SqlConnectionRetryPolicy);
}
public static IEnumerable<T> QueryWithRetry<T>(
this SqlConnection cnn, string sql, object param = null, IDbTransaction transaction = null,
bool buffered = true, int? commandTimeout = null, CommandType? commandType = null
)
{
return SqlCommandRetryPolicy.ExecuteAction(
() => cnn.Query<T>(sql, param, transaction, buffered, commandTimeout, commandType)
);
}
}
}
【问题讨论】: