下面展示一些 内联代码片
。
package my.common.utils;
import java.util.function.Function;
import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
/**
* RetryUtils
*/
public class RetryUtils {
/**
* 重试
*/
public static <T, R> R retry(Function<T, R> func, T request, String name, int maxAttempts,
long initialIntervalMillis) {
return retry(func, request, name, maxAttempts, initialIntervalMillis, IntervalFunction.DEFAULT_MULTIPLIER,
IntervalFunction.DEFAULT_RANDOMIZATION_FACTOR);
}
/**
* 重试
*/
public static <T, R> R retry(Function<T, R> func, T request, String name, int maxAttempts,
long initialIntervalMillis, Class<? extends Throwable> exception) {
return retry(func, request, name, maxAttempts, initialIntervalMillis, IntervalFunction.DEFAULT_MULTIPLIER,
IntervalFunction.DEFAULT_RANDOMIZATION_FACTOR,exception);
}
/**
* 重试
*/
public static <T, R> R retry(Function<T, R> func, T request, String name, int maxAttempts,
long initialIntervalMillis, double multiplier, double randomizationFactor) {
IntervalFunction intervalFn =
IntervalFunction.ofExponentialRandomBackoff(initialIntervalMillis, multiplier, randomizationFactor);
RetryConfig retryConfig = RetryConfig.custom()
.maxAttempts(maxAttempts)
.intervalFunction(intervalFn)
.build();
Retry retry = Retry.of(name, retryConfig);
Function<T, R> retryFn = Retry.decorateFunction(retry, func);
return retryFn.apply(request);
}
/**
* 重试
*/
public static <T, R> R retry(Function<T, R> func, T request, String name, int maxAttempts,
long initialIntervalMillis, double multiplier, double randomizationFactor,
Class<? extends Throwable> exception) {
IntervalFunction intervalFn =
IntervalFunction.ofExponentialRandomBackoff(initialIntervalMillis, multiplier, randomizationFactor);
RetryConfig retryConfig = RetryConfig.custom()
.maxAttempts(maxAttempts)
.retryExceptions(exception)
.intervalFunction(intervalFn)
.build();
Retry retry = Retry.of(name, retryConfig);
Function<T, R> retryFn = Retry.decorateFunction(retry, func);
return retryFn.apply(request);
}
}
try {
RetryUtils.retry(this::doGet,objectDto,"RetryName", 3,
5000L, UserDefindException.class);
}catch (UserDefindException e) {
//TODO 处理
}
}
private boolean doGet(ObjectDTO objectDto) throws UserDefindException {
throw new UserDefindException();
return true;
}