我已经实现了一个通用存储库,并且想知道在死锁异常的情况下是否有一种智能方法来实现重试逻辑?
对于所有存储库方法,该方法应该相同。那么无论如何我可以避免在每一种方法中使用retry-count'再次编写'try / catch - call方法'吗?
欢迎任何建议。
我的存储库代码:
public class GenericRepository : IRepository
{
private ObjectContext _context;
public List<TEntity> ExecuteStoreQuery<TEntity>(string commandText, params object[] parameters) where TEntity : class
{
List<TEntity> myList = new List<TEntity>();
var groupData = _context.ExecuteStoreQuery<TEntity>(commandText, parameters);
return myList;
}
public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
{
var entityName = GetEntityName<TEntity>();
return _context.CreateQuery<TEntity>(entityName);
}
public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
{
return GetQuery<TEntity>().AsEnumerable();
}
编辑:
1.解决方案:
稍微修改了 chris.house.00 的解决方案
public static T DeadlockRetryHelper<T>(Func<T> repositoryMethod, int maxRetries)
{
var retryCount = 0;
while (retryCount < maxRetries)
{
try
{
return repositoryMethod();
}
catch (System.Data.SqlClient.SqlException ex)
{
if (ex.Number == 1205)// Deadlock
retryCount++;
else
throw;
}
}
return default(T);
}
你这样称呼它:
public TEntity FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
return RetryUtility.DeadlockRetryHelper<TEntity>( () =>p_FirstOrDefault<TEntity>(predicate), 3);
}
protected TEntity p_FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
return GetQuery<TEntity>().FirstOrDefault<TEntity>(predicate);
}
答案 0 :(得分:34)
这样的事情怎么样:
public T DeadlockRetryHelper<T>(Func<T> repositoryMethod, int maxRetries)
{
int retryCount = 0;
while (retryCount < maxRetries)
{
try
{
return repositoryMethod();
}
catch (SqlException e) // This example is for SQL Server, change the exception type/logic if you're using another DBMS
{
if (e.Number == 1205) // SQL Server error code for deadlock
{
retryCount++;
}
else
{
throw; // Not a deadlock so throw the exception
}
// Add some code to do whatever you want with the exception once you've exceeded the max. retries
}
}
}
使用上面的代码,您的重试逻辑都在此方法中,您可以将您的存储库方法作为委托传递。
答案 1 :(得分:22)
我知道这是一篇旧帖子,但想分享一个更新的答案。
EF 6现在有一个内置的解决方案,您可以设置执行策略,这将是一次性实现。您创建一个继承自DbExectutionStrategy的类并重写ShouldRetryOn虚方法。您可以创建一个包含常量字段值的异常的静态类,它们是重试符合条件的代码并循环遍历每个异常,以确定抛出的当前sql异常是否与符合条件的重试代码列表匹配...
public static class SqlRetryErrorCodes
{
public const int TimeoutExpired = -2;
public const int Deadlock = 1205;
public const int CouldNotOpenConnection = 53;
public const int TransportFail = 121;
}
public class MyCustomExecutionStrategy : DbExecutionStrategy
{
public MyCustomExecutionStrategy(int maxRetryCount, TimeSpan maxDelay) : base(maxRetryCount, maxDelay) { }
private readonly List<int> _errorCodesToRetry = new List<int>
{
SqlRetryErrorCodes.Deadlock,
SqlRetryErrorCodes.TimeoutExpired,
SqlRetryErrorCodes.CouldNotOpenConnection,
SqlRetryErrorCodes.TransportFail
};
protected override bool ShouldRetryOn(Exception exception)
{
var sqlException = exception as SqlException;
if (sqlException != null)
{
foreach (SqlError err in sqlException.Errors)
{
// Enumerate through all errors found in the exception.
if (_errorCodesToRetry.Contains(err.Number))
{
return true;
}
}
}
return false;
}
}
最后一次,您已经设置了自定义执行策略,您只需使用设置执行策略的公共构造函数创建另一个继承自DbConfiguration的类:
public class MyEfConfigurations : DbConfiguration
{
public MyEfConfigurations()
{
SetExecutionStrategy("System.Data.SqlClient",() => new MyCustomExecutionStrategy(5,TimeSpan.FromSeconds(10)));
}
}
答案 2 :(得分:2)
解决方案有效但我不必担心将退休的Action
或Func
的参数数量。如果使用泛型Action
创建单个重试方法,则可以处理要在lambda中调用的方法的所有可变性:
public static class RetryHelper
{
public static void DeadlockRetryHelper(Action method, int maxRetries = 3)
{
var retryCount = 0;
while (retryCount < maxRetries)
{
try
{
method();
return;
}
catch (System.Data.SqlClient.SqlException ex)
{
if (ex.Number == 1205)// Deadlock
{
retryCount++;
if (retryCount >= maxRetries)
throw;
// Wait between 1 and 5 seconds
Thread.Sleep(new Random().Next(1000, 5000));
}
else
throw;
}
}
}
}
然后像这样使用它:
RetryHelper.DeadlockRetryHelper(() => CopyAndInsertFile(fileModel));
答案 3 :(得分:2)
EntityFramework 6
添加ExecutionStrategy
功能。所需要的只是正确设置策略。
我的重试政策:
public class EFRetryPolicy : DbExecutionStrategy
{
public EFRetryPolicy() : base()
{
}
//Keep this constructor public too in case it is needed to change defaults of exponential back off algorithm.
public EFRetryPolicy(int maxRetryCount, TimeSpan maxDelay): base(maxRetryCount, maxDelay)
{
}
protected override bool ShouldRetryOn(Exception ex)
{
bool retry = false;
SqlException sqlException = ex as SqlException;
if (sqlException != null)
{
int[] errorsToRetry =
{
1205, //Deadlock
-2, //Timeout
};
if (sqlException.Errors.Cast<SqlError>().Any(x => errorsToRetry.Contains(x.Number)))
{
retry = true;
}
}
return retry;
}
}
告诉EF应用我的策略:
public class EFPolicy: DbConfiguration
{
public EFPolicy()
{
SetExecutionStrategy(
"System.Data.SqlClient",
() => new EFRetryPolicy());
}
}
来源:
重试策略不适用于用户发起的交易(使用TransactionScope
创建的交易),如here所述。如果使用,您将收到错误The configured execution strategy does not support user initiated transactions
答案 4 :(得分:1)
您是否考虑过某种形式的政策注入?您可以使用Unity拦截(仅作为示例)捕获所有存储库调用。然后你只需在拦截器中编写一次重试逻辑,而不是在每种方法中重复多次。
答案 5 :(得分:0)
我在上面的帖子中使用了MiguelSlv提供的以下解决方案,它按预期对我有用。简单易行。
EntityFramework 6添加了ExecutionStrategy功能。所有需要做的就是正确设置策略。
我的重试政策:
public class EFRetryPolicy : DbExecutionStrategy
{
public EFRetryPolicy() : base()
{
}
//Keep this constructor public too in case it is needed to change defaults of exponential back off algorithm.
public EFRetryPolicy(int maxRetryCount, TimeSpan maxDelay): base(maxRetryCount, maxDelay)
{
}
protected override bool ShouldRetryOn(Exception ex)
{
bool retry = false;
SqlException sqlException = ex as SqlException;
if (sqlException != null)
{
int[] errorsToRetry =
{
1205, //Deadlock
-2, //Timeout
};
if (sqlException.Errors.Cast<SqlError>().Any(x => errorsToRetry.Contains(x.Number)))
{
retry = true;
}
}
return retry;
}
}
告诉EF应用此政策
public class EFPolicy: DbConfiguration
{
public EFPolicy()
{
SetExecutionStrategy(
"System.Data.SqlClient",
() => new EFRetryPolicy());
}
}
来源:
使用实体框架6实现连接弹性 Microsoft文档 如此处所述,重试策略不适用于用户启动的事务(使用TransactionScope创建的事务)。如果使用该错误,则会收到错误消息。配置的执行策略不支持用户启动的事务