Implement a retry policy in asp.net core

时间:2016-07-11 23:27:58

标签: c# asp.net-core

What is the simplest way to implement a retry policy in asp.net core ? The idea is simple, if some particular type of exceptions is raised ( say sql deadlock ), we retry the httprequest for a maximum of N times.

I use a middleware for som custom authentication, I don't know if a middleware is the best choice for this kind of mechanism ( I'm new to the pipeline architecture, I have read that there are several types of components : Singletons, per-request etc ..).

UPDATE: Sql deadlock is given here just as an example, my application has only restful webservices in it, each request is very short and runs entirely in a Serializable Sql Transaction ( there is no other side effects which I can't rollback like sending email or deleting a File... ). Because I'm using transactions, and because I can't garantee that my transactions will always use the tables in the same order ( It depends on who calls the webservices ), deadlock is inavoidable, so I need to have a retry policy of all the httprequest. ( The question is not about transactions and deadlocks but how to implement a retry police in asp.net core )

2 个答案:

答案 0 :(得分:6)

您可以使用Polly等开箱即用的工具。

  

Polly是一个.NET 3.5 / 4.0 / 4.5 / PCL库,允许开发人员以流畅的方式表达瞬态异常和故障处理策略,如重试,重试,等待和重试或断路器。

在您的特定情况下,示例可能是:

Policy
  .Handle<SqlException>(ex => ex.Number == 1205) // sql deadlock
  .Retry(3, (exception, retryCount) =>
  {
     // do something 
  });

虽然我不确定你的sql死锁和web请求是如何相互关联的。我认为你会重新响应http状态代码的http请求。例如,以下策略然后添加如何处理这些条件:

Policy
  .HandleResult<HttpStatusCode>(HttpStatusCode.InternalServerError)
  .OrResult<HttpStatusCode>(HttpStatusCode.BadGateway)

答案 1 :(得分:1)

取决于您想要重试的级别。让我们说数据库操作失败了。您是要重试整个请求(包括所有开销)还是仅仅执行该操作?

根据您希望重试的级别,您可能会找到一个或多个更合适的解决方案。

您总是可以通过重新调用管道中的中间件之后的组件来重新启动中间件级别,但要记住的是,您无法盲目重试(我会害怕这样做)因为代码无法为此设计...

就像Luke Hutton所说,可能Polly是你可以使用的东西。