Polly中调用异步方法的方式
2018-07-11 本文已影响15人
Weidaicheng
最近在看Refit,一个还不错的REST API调用类库(我调用的API也无非是简单的增删改查),因为删除的时候会存在ID不存在的情况,所以就在调用的时候加入了Polly来进行删除的异常处理。
先来看一下后台的API代码
[Produces("application/json")]
[Route("api/Author")]
[ApiExplorerSettings(GroupName = "v1")]
public class AuthorController : Controller
{
private readonly SwaggerDemoContext _swaggerDemoContext;
public AuthorController(SwaggerDemoContext swaggerDemoContext)
{
_swaggerDemoContext = swaggerDemoContext;
}
// GET api/values
[HttpGet]
public IEnumerable<Author> Get()
{
var authors = _swaggerDemoContext.Authors.ToList();
return authors;
}
// GET api/values/5
[HttpGet("{id}")]
public Author Get([FromRoute]int id)
{
var author = _swaggerDemoContext.Authors.Find(id);
return author;
}
// POST api/values
[HttpPost]
public void Post([FromBody] Author author)
{
_swaggerDemoContext.Authors.Add(author);
_swaggerDemoContext.SaveChanges();
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put([FromRoute]int id, [FromBody] Author author)
{
author.Id = id;
_swaggerDemoContext.Authors.Update(author);
_swaggerDemoContext.SaveChanges();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete([FromRoute]int id)
{
var author = _swaggerDemoContext.Authors.Find(id);
_swaggerDemoContext.Authors.Remove(author);
_swaggerDemoContext.SaveChanges();
}
}
Refti的接口调用接口代码
public interface IAuthorApi
{
[Get("/api/Author")]
Task<IEnumerable<Author>> GetAuthors();
[Get("/api/Author/{id}")]
Task<Author> GetAuthor(int id);
[Post("/api/Author")]
Task PostAuthor([Body]Author author);
[Put("/api/Author/{id}")]
Task PutAuthor(int id, [Body]Author author);
[Delete("/api/Author/{id}")]
Task DeleteAuthor(int id);
}
在调用接口的时候Polly始终不能正确的抓取并处理异常,Polly处理部分代码如下:
private async static void foo()
{
var authorApi = RestService.For<IAuthorApi>("http://localhost:8794");
var delId = 2;
await Policy
.Handle<ApiException>()
.RetryForever(ex =>
{
delId++;
})
.Execute(() => authorApi.DeleteAuthor(delId));
}
其中想要的是Id不存在(删除异常)时继续删除删除下一个Id,运行时Polly并不能正确的进行处理
unhandled exception.png
解决方法
Polly中调用异步方法要使用ExecuteAsync而不是Execute,同时需要修改处理方法为Async,代码修改如下:
await Policy
.Handle<ApiException>()
.RetryForeverAsync((ex, count) =>
{
delId++;
})
.ExecuteAsync(() => authorApi.DeleteAuthor(delId));
可以正常运行
success.png
后记
Polly对异步方法的支持点击查看
WebApi项目地址
调用客户端项目地址