Contents
  1. 1. Multiple attempts to get the result

Multiple attempts to get the result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class LogicProcessingUtils {
/**
* @param maxTryTimes
* @param successPredicate
* @param function
* @param params parameter object
* @param <T> function return type
* @param <P> function parameter type
* @return
*/
public static <T, P> T tryToGetResult(int maxTryTimes,
Predicate<T> successPredicate,
Function<P, T> function,
P param) {
int tryTimes = 0;
T t = null;
while (tryTimes < maxTryTimes) {
t = function.apply(param);
// System.out.println(t);
if (successPredicate.test(t)) {
break;
}
tryTimes++;
}
return t;
}

public static <T> T tryToGetResult(int maxTryTimes,
Predicate<T> successPredicate,
Supplier<T> supplier) {
int tryTimes = 0;
T t = null;
while (tryTimes < maxTryTimes) {
t = supplier.get();
// System.out.println(t);
if (successPredicate.test(t)) {
break;
}
tryTimes++;
}
return t;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
int maxTryTimes = 3;
ObjectNode result = LogicProcessingUtils.tryToGetResult(
maxTryTimes,
jsonNode -> jsonNode.get("code").asInt() == 200,
myTest::getResult,
0);
System.out.println(result);
}

public ObjectNode getResult(Object param) {
System.out.println("param: " + param);
ThreadLocalRandom random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(10);
System.out.println("random number: " + randomNumber);
String jsonStr = "{\"code\":500,\"data\":%d,\"msg\":\"请求失败\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
return (ObjectNode) objectMapper.readTree(String.format(jsonStr, randomNumber));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
Contents
  1. 1. Multiple attempts to get the result