ASP.NET C#MySQL查询执行失败后重试

时间:2017-10-02 13:31:07

标签: c# mysql asp.net dapper

是否有任何ASP.NET包/ DLL允许MySQL查询执行失败时重试?

我已经阅读了Transient Fault Handling ,甚至遇到了Dapper issue which shows an example但是从我的研究中看,这只适用于SqlServer和/或Azure。

我的技术堆栈如下:

  • .NET 4.5.2
  • Dapper 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)
                );
        }
    }
}

1 个答案:

答案 0 :(得分:1)

发布此消息后不久,我发现了一个名为Polly的软件包似乎解决了这个“重试”问题。我通过StackOverflow question跟踪了它。

这是我从MySQL数据库查询并在失败时重试的实现:

var policy = Policy
    .Handle<AuthenticationException>(ex => ex.InnerException is Win32Exception)
    .Or<AuthenticationException>()
    .Retry((exception, attempt) =>
    {                        
        Log.Error(exception, "Class: {Class} | Method: {Method} | Failure executing query, on attempt number: {Attempt}", GetType().Name,
            MethodBase.GetCurrentMethod().Name, attempt);
    });

try
{
    var token = new Token();

    policy.Execute(() =>
    {
        using (var connection = _mySqlDatabase.GetConnection())
        {
            token = connection.Query<Token>("SELECT * FROM Token...").FirstOrDefault();
        }
    });

    return token;
}
catch (Exception ex)
{
    Log.Error(ex, "Class: {Class} | Method: {Method} | Ultimately failed to retrieve data from the database", GetType().Name,
        MethodBase.GetCurrentMethod().Name);
    throw new HttpError(HttpStatusCode.InternalServerError);
}