forked from nibnait/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRetryUtils.java
More file actions
76 lines (69 loc) · 2.37 KB
/
RetryUtils.java
File metadata and controls
76 lines (69 loc) · 2.37 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
69
70
71
72
73
74
75
76
package common.util;
import common.bo.BaseResponse;
import common.enums.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import java.util.function.Supplier;
/**
* Created by nibnait on 2021/10/21
*/
@Slf4j
public class RetryUtils {
/**
* 无返回值的重试 num 次
* @param runnable 一个匿名函数:() -> xx.xxx
* @param num 重试次数
* @param errorMsg 报错信息
* @param sleepMillis 每次重试间隔的毫秒数
*/
public static void retryRunnable(Runnable runnable, int num, String errorMsg, Long sleepMillis) {
boolean isFail = true;
int count = 0;
while (isFail && count < num) {
isFail = false;
try {
runnable.run();
} catch (Exception e) {
isFail = true;
count ++ ;
log.error(DataUtils.format("第 {} 次重试 {}", count, errorMsg), e);
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException ex) {
log.warn(ex.getMessage(), ex);
Thread.currentThread().interrupt();
}
}
}
}
/**
* 带返回值的重试 num 次
* @param supplier 一个匿名函数:() -> xx.xxx
* @param num 重试次数
* @param errorMsg 报错信息
* @param sleepMillis 每次重试间隔的毫秒数
*/
public static BaseResponse retrySupplier(Supplier<BaseResponse> supplier, int num, String errorMsg, Long sleepMillis) {
boolean isFail = true;
int count = 0;
while (isFail && count < num) {
isFail = false;
try {
BaseResponse baseResponse = supplier.get();
if (ErrorCode.SUCCESS.getCode().equals(baseResponse.code)) {
return baseResponse;
}
} catch (Exception e) {
isFail = true;
count ++ ;
log.error(DataUtils.format("第 {} 次重试 {}", count, errorMsg), e);
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException ex) {
log.warn(ex.getMessage(), ex);
Thread.currentThread().interrupt();
}
}
}
return new BaseResponse(ErrorCode.SERVICE_ERROR, errorMsg);
}
}