RetryUtils.java
2.07 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.jfinal.weixin.sdk.utils;
import com.jfinal.kit.LogKit;
/**
* 异常重试工具类
* @author L.cm
*/
public class RetryUtils {
/**
* 回调结果检查
*/
public interface ResultCheck {
boolean matching();
String getJson();
}
/**
* 在遇到异常时尝试重试
* @param retryLimit 重试次数
* @param retryCallable 重试回调
* @param <V> 泛型
* @return V 结果
*/
public static <V extends ResultCheck> V retryOnException(int retryLimit,
java.util.concurrent.Callable<V> retryCallable) {
V v = null;
for (int i = 0; i < retryLimit; i++) {
try {
v = retryCallable.call();
} catch (Exception e) {
LogKit.warn("retry on " + (i + 1) + " times v = " + (v == null ? null : v.getJson()) , e);
}
if (null != v && v.matching()) break;
LogKit.error("retry on " + (i + 1) + " times but not matching v = " + (v == null ? null : v.getJson()));
}
return v;
}
/**
* 在遇到异常时尝试重试
* @param retryLimit 重试次数
* @param sleepMillis 每次重试之后休眠的时间
* @param retryCallable 重试回调
* @param <V> 泛型
* @return V 结果
* @throws java.lang.InterruptedException 线程异常
*/
public static <V extends ResultCheck> V retryOnException(int retryLimit, long sleepMillis,
java.util.concurrent.Callable<V> retryCallable) throws java.lang.InterruptedException {
V v = null;
for (int i = 0; i < retryLimit; i++) {
try {
v = retryCallable.call();
} catch (Exception e) {
LogKit.warn("retry on " + (i + 1) + " times v = " + (v == null ? null : v.getJson()) , e);
}
if (null != v && v.matching()) break;
LogKit.error("retry on " + (i + 1) + " times but not matching v = " + (v == null ? null : v.getJson()));
Thread.sleep(sleepMillis);
}
return v;
}
}