-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRetryDemo.java
More file actions
75 lines (64 loc) · 1.71 KB
/
RetryDemo.java
File metadata and controls
75 lines (64 loc) · 1.71 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
package com.retry;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;
/**
* 重试
*
* 服务不稳定的时候,可以重试。
*
*/
@Slf4j
public class RetryDemo {
public static void main(String[] args) throws InterruptedException {
retryDoSomething();
}
public static void retryDoSomething() throws InterruptedException {
log.info("retryDoSomething start.");
//重试次数
int maxTimes = 5;
//每次重试间隔时间
int interval = 500;
for (int i = 0; i <= maxTimes; i++) {
boolean isOk = doSomething();
//成功了就停止
if (isOk ) {
break;
}
//失败就间隔一段时间后再执行
Thread.sleep(interval);
}
log.info("retryDoSomething end.");
}
/**
* 执行逻辑,成功就返回 true,报错返回 false
*
* @return
*/
public static boolean doSomething() {
try {
//执行逻辑
doSth();
} catch (Exception e) {
log.error("service.doSomething() error.", e);
return false;
}
return true;
}
/**
* 执行逻辑的方法
*
* 以下是示例,可以将示例替换成自己的逻辑
*
*/
private static void doSth() {
Random random = new Random();
//随机产生一个[0-100]之间的随机数,由于是随机,每次执行的结果可能不一样
int num = random.nextInt(101);
if (num % 5 ==0) {
log.info("doSth num:"+ num);
} else {
//模拟失败,抛异常
throw new NumberFormatException();
}
}
}