|
@@ -2,7 +2,9 @@ package com.tzld.piaoquan.content.understanding.util;
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
|
|
|
+import java.util.Objects;
|
|
import java.util.concurrent.TimeUnit;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
+import java.util.function.Function;
|
|
import java.util.function.LongSupplier;
|
|
import java.util.function.LongSupplier;
|
|
import java.util.function.Predicate;
|
|
import java.util.function.Predicate;
|
|
import java.util.function.Supplier;
|
|
import java.util.function.Supplier;
|
|
@@ -21,7 +23,7 @@ public class RetryUtil {
|
|
* @return
|
|
* @return
|
|
*/
|
|
*/
|
|
public static <T> T executeWithRetry(Supplier<T> action, String actionName) {
|
|
public static <T> T executeWithRetry(Supplier<T> action, String actionName) {
|
|
- return executeWithRetry(action, MAX_RETRIES, actionName);
|
|
|
|
|
|
+ return executeWithRetry(action, MAX_RETRIES, actionName, null);
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
/**
|
|
@@ -34,12 +36,35 @@ public class RetryUtil {
|
|
* @return
|
|
* @return
|
|
*/
|
|
*/
|
|
public static <T> T executeWithRetry(Supplier<T> action, Integer maxRetries, String actionName) {
|
|
public static <T> T executeWithRetry(Supplier<T> action, Integer maxRetries, String actionName) {
|
|
|
|
+ return executeWithRetry(action, maxRetries, actionName, null);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 重试
|
|
|
|
+ * @param action
|
|
|
|
+ * @param maxRetries
|
|
|
|
+ * @param actionName
|
|
|
|
+ * @param retryIntervalProvider 毫秒
|
|
|
|
+ * @return
|
|
|
|
+ * @param <T>
|
|
|
|
+ */
|
|
|
|
+ public static <T> T executeWithRetry(Supplier<T> action, Integer maxRetries, String actionName, Function<Integer, Long> retryIntervalProvider) {
|
|
for (int i = 1; i <= maxRetries; i++) {
|
|
for (int i = 1; i <= maxRetries; i++) {
|
|
try {
|
|
try {
|
|
return action.get();
|
|
return action.get();
|
|
} catch (Exception e) {
|
|
} catch (Exception e) {
|
|
log.error("{} failed on attempt {}: {}", actionName, i, e.getMessage(), e);
|
|
log.error("{} failed on attempt {}: {}", actionName, i, e.getMessage(), e);
|
|
if (i < maxRetries) {
|
|
if (i < maxRetries) {
|
|
|
|
+ if (Objects.nonNull(retryIntervalProvider) && Objects.nonNull(retryIntervalProvider.apply(i))) {
|
|
|
|
+ long interval = retryIntervalProvider.apply(i);
|
|
|
|
+ if (interval > 0) {
|
|
|
|
+ try {
|
|
|
|
+ TimeUnit.MILLISECONDS.sleep(interval);
|
|
|
|
+ } catch (InterruptedException ex) {
|
|
|
|
+ log.error("{} failed on attempt {}: {}", actionName, i, ex.getMessage(), ex);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
log.info("{} will be retried (attempt {}/{})", actionName, i + 1, maxRetries);
|
|
log.info("{} will be retried (attempt {}/{})", actionName, i + 1, maxRetries);
|
|
} else {
|
|
} else {
|
|
log.error("{} failed after {} retries due to non-IO error.", actionName, maxRetries);
|
|
log.error("{} failed after {} retries due to non-IO error.", actionName, maxRetries);
|