我正在从REST服务中读取并需要为一个使用频繁的服务处理“等待并重试”,这会给我一个错误:
Too many queries per second
要么
Server Busy
一般来说,由于我有许多REST服务要调用,我怎么能一般地处理发生异常时会发生的退避逻辑呢?
有没有内置的框架?我只是想编写干净的代码,不要太担心管道和基础设施.
解决方法
您可以在一个处理重试逻辑的方法中将尝试包装起来.例如,如果您使用的是WebClient的异步方法:
- public async Task<T> RetryQuery<T>(Func<Task<T>> operation,int numberOfAttempts,int msecsBetweenRetries = 500)
- {
- while (numberOfAttempts > 0)
- {
- try
- {
- T value = await operation();
- return value;
- }
- catch
- {
- // Failed case - retry
- --numberOfAttempts;
- }
- await Task.Delay(msecsBetweenRetries);
- }
- throw new ApplicationException("Operation Failed repeatedly");
- }
然后你可以通过以下方式使用:
- // Try 3 times with 500 ms wait times in between
- string result = await RetryQuery(async () => webClient.DownloadStringTaskAsync(url),3);