目录
一、retry工具类
提供函数式接口默认实现,开发者也可以自己实现
package com.example.demo.util;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class RetryUtils {
public static <T> T retryWhenNull(RetryContent<T> handler, long timeoutMills, long intervalMills) {
while (timeoutMills > 0) {
T result = handler.retry();
if (result != null) {
return result;
}
try {
TimeUnit.MILLISECONDS.sleep(intervalMills);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeoutMills -= intervalMills;
}
return null;
}
public static <T> T retryWhenRuntimeException(RetryContent<T> handler, long timeoutMills, long intervalMills) {
while (timeoutMills > 0) {
try {
return handler.retry();
} catch (RuntimeException e1) {
e1.printStackTrace();
try {
TimeUnit.MILLISECONDS.sleep(intervalMills);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
timeoutMills -= intervalMills;
} catch (Exception e3) {
return null;
}
}
return null;
}
public interface RetryContent<T> {
RetryContent<Integer> DEFAULT = () -> {
int i = new Random().nextInt();
System.out.println(i);
return i > 10 ? i : null;
};
T retry();
}
public static void main(String[] args) {
Integer random = RetryUtils.retryWhenNull(RetryContent.DEFAULT, 5000, 500);
System.out.println("result is " + random);
}
}
二、测试与效果
public static void main(String[] args) {
Integer num1 = RetryUtils.retryWhenNull(() -> {
int n = new Random().nextInt(10);
System.out.println("产生随机数:"+n);
return n > 5 ? n : null;
}, 60000, 1000);
System.out.println("获得随机数"+num1);
Integer num2 = RetryUtils.retryWhenRuntimeException(() -> {
int n = new Random().nextInt(10);
System.out.println("产生随机数:"+n);
if (n < 5) {
throw new RuntimeException("小于5异常");
}else {
return n;
}
}, 60000, 1000);
System.out.println("获得随机数"+num2);
}
产生随机数:4
产生随机数:2
产生随机数:1
产生随机数:5
产生随机数:6
获得随机数6
产生随机数:2
java.lang.RuntimeException: 小于5异常
at com.jwolf.RetryUtils.lambda$main$1(RetryUtils.java:58)
at com.jwolf.RetryUtils$$Lambda$2/1023892928.retry(Unknown Source)
at com.jwolf.RetryUtils.retryWhenRuntimeException(RetryUtils.java:29)
at com.jwolf.RetryUtils.main(RetryUtils.java:54)
产生随机数:4
java.lang.RuntimeException: 小于5异常
at com.jwolf.RetryUtils.lambda$main$1(RetryUtils.java:58)
at com.jwolf.RetryUtils$$Lambda$2/1023892928.retry(Unknown Source)
at com.jwolf.RetryUtils.retryWhenRuntimeException(RetryUtils.java:29)
at com.jwolf.RetryUtils.main(RetryUtils.java:54)
产生随机数:7
获得随机数7Process finished with exit code 0