重试
重试,就是多试几次。一次不成功,多试几次说不定就成功了。
什么时候重试?
要执行的逻辑比较重要,或者是服务不稳定,或者是Rpc远程调服务有时不成功,都可以使用重试。
示例代码
public class RetryTest {
private static final Logger log = Logger.getLogger(RetryTest.class);
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 <= 5="=0)" maxtimes; i++) { boolean isok="doSomething();" 成功了就停止 if (isok ) break; } thread.sleep(interval); log.info("retrydosomething end."); ** * 执行逻辑,成功就返回 true,报错返回 false @return public static dosomething() try 执行逻辑 dosth(); catch (exception e) log.error("service.dosomething() error.", e); return false; true; 执行逻辑的方法 以下是示例,可以将示例替换成自己的逻辑 void dosth() random random(); 随机产生一个[0-100]之间的随机数,由于是随机,每次执行的结果可能不一样 int num="random.nextInt(101);" (num % 如果是5的倍数就不报错 log.info("dosth num:"+ num); else 模拟失败,抛异常 throw new numberformatexception(); < code></=>
Original: https://www.cnblogs.com/expiator/p/16483047.html
Author: 乐之者v
Title: java重试
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/538794/
转载文章受原作者版权保护。转载请注明原作者出处!