gpt4 book ai didi

java - 如何使用 Java 重试函数调用?

转载 作者:行者123 更新时间:2023-12-02 01:33:40 25 4
gpt4 key购买 nike

我正在使用自定义 Java 库来进行 REST API 调用。我有使用该库进行 api 调用的函数。我希望能够重试一些 api 调用/函数,但该库不提供该功能。

我想重试 api 调用 n 次,或者重试一定时间,在每次执行之间暂停 x 秒。在所有情况下,仅应重试 api 调用,直到满足某些条件,例如 Response(类)对象响应代码 == 200 并且响应正文包含“成功!!!”。我还希望能够在进行这些调用时忽略某些异常。

我需要的伪代码:

    SuperLibrary superLibrary = new SuperLibrary();
superLibrary.do(myApiCallFunction()).
.handle(ConnectException.class)
.withDelay(Duration.ofSeconds(3))
//.withMaxTimeout(Duration.ofSeconds(15))//Also an option
.withMaxRetries(3)
.until(Some Conditions are true);

有没有可靠且“简单”的java库可以让我做到这一点?如果有人能给我指出任何可以满足我需要的代码示例,我将不胜感激。

谢谢!

最佳答案

我使用 java8 中的函数并编写 RetryHelp 来执行此操作

package com.river.reytry;

import java.util.function.Supplier;

/**
* @author riverfan
* @date 2019-07-19
*/
public class RetryHelp {
private int num = 1;
private Supplier<Boolean> consumer;
private long intervalTime = 0;
private Supplier<RuntimeException> exceptionSupplier;

public static RetryHelp build() {
return new RetryHelp();
}

public RetryHelp tryWith(Supplier<Boolean> t) {
this.consumer = t;
return this;
}

public RetryHelp tryInterval(long time) {
intervalTime = time;
return this;
}

public RetryHelp tryNum(int num) {
this.num = num;
return this;
}

public RetryHelp elseThrow(Supplier<RuntimeException> exceptionSupplier) {
this.exceptionSupplier = exceptionSupplier;
return this;
}

public void start() throws RuntimeException {
for (int i = 0; i < num; i++) {

if (consumer.get()) {
return;
}
//最后一次不用sleep
if(i == num-1){
continue;
}
try {
Thread.sleep(intervalTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//System.out.println("no success throw exception");
if(exceptionSupplier == null){
return;
}
throw exceptionSupplier.get();
}


}

测试是这样的


import org.apache.commons.lang3.RandomUtils;

public class RetryHelpTest {

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println("--------------");
RetryHelp.build()
.tryWith(() -> {
System.out.println("hello world");
return RandomUtils.nextBoolean();
})
.tryInterval(1L)
.tryNum(3)
.elseThrow(() -> new RuntimeException("some thing wrong"))
.start();
}
}
}

关于java - 如何使用 Java 重试函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com