能够接收异常参数的一段通用的重试代码
时间: 2024-03-08 09:47:12 浏览: 26
以下是一段通用的重试代码,可以接收异常参数,支持在异常发生时进行重试操作:
```java
public static <T> T retryOnException(Supplier<T> supplier, int maxAttempts, long delay, Class<? extends Throwable> exceptionClass) throws Exception {
int attempt = 1;
while (true) {
try {
return supplier.get();
} catch (Exception e) {
if (!exceptionClass.isInstance(e) || attempt >= maxAttempts) {
throw e;
}
Thread.sleep(delay);
attempt++;
}
}
}
```
该方法接收三个参数:
- `supplier`:一个返回值类型为T的函数式接口,代表需要进行重试的操作。
- `maxAttempts`:最大重试次数。
- `delay`:每次重试的间隔时间。
- `exceptionClass`:需要捕获的异常类型。
该方法在每次执行 `supplier.get()` 方法时,会捕获 `exceptionClass` 类型的异常,并进行重试操作,最多重试 `maxAttempts` 次。每次重试后会暂停 `delay` 毫秒。如果超过最大重试次数或者捕获的异常不属于 `exceptionClass` 类型,则会将异常抛出。
使用该方法时,只需要将需要进行重试的操作放在一个lambda表达式中,并将该lambda表达式作为参数传入即可,例如:
```java
retryOnException(() -> {
// 需要进行重试的操作
return null;
}, 3, 1000, IOException.class);
```
该代码会在发生 `IOException` 异常时进行最多3次重试,每次间隔1秒。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)