@FunctionalInterface
public interface Supplier<T> {
T get();
}
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
class ConfigDataResponse {
private Integer ret;
private String msg;
private Map<String, String> data;
public Integer getRet() {
return ret;
}
public void setRet(Integer ret) {
this.ret = ret;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
@Override
public String toString() {
return "ConfigDataResponse{" +
"ret=" + ret +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
public class RetryService {
public <RESULT_TYPE> RESULT_TYPE doWithRetry(Supplier<RESULT_TYPE> invoker, Predicate<RESULT_TYPE> isSuccess, Function<RESULT_TYPE, ? extends RuntimeException> callWhenFail) {
RESULT_TYPE lastResult = null;
for (int tryTimes = 0; tryTimes < 2; ++tryTimes) {
if (tryTimes > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
lastResult = invoker.get();
if (isSuccess.test(lastResult)) {
return lastResult;
}
}
throw callWhenFail.apply(lastResult);
}
public static void main(String[] args) {
RetryService retryService = new RetryService();
ConfigDataResponse result = retryService.doWithRetry(() -> {
String json = "{\"ret\":0,\"msg\":\"success\",\"data\":{\"env\":\"test\"}}";
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, ConfigDataResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}, configDataResponse -> configDataResponse != null && Integer.valueOf(0).equals(configDataResponse.getRet()), configDataResponse -> {
throw new RuntimeException(configDataResponse.getMsg());
});
System.out.println(result);
}
}