gpt4 book ai didi

java - 在不同的函数中使用相同的 while 循环

转载 作者:行者123 更新时间:2023-12-01 17:43:04 24 4
gpt4 key购买 nike

我在两个不同的函数中有一个非常相似的 while 循环,我如何编写两个函数使用相同 while 的代码?这个想法是,当我进入任何一个函数时,它们应该实现在放弃之前重试 5 次的行为。

    public Document getHtml(String url) {
int retries = 0;
while (retries < 5) {
try {
return Jsoup.connect(url).get();
} catch(IOException e) {
LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
}
retries += 1;
}
return null;
}

@Override
public String getFile(String url) {
int retries = 0;
while(retries < 5) {
try {
URL urlObj = new URL(url);
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try (InputStream is = urlObj.openStream()) {
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
}
return result.toString("UTF-8");
} catch (IOException e) {
LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
}
retries += 1;
}
return null;
}

最佳答案

您可以将重试逻辑提取到高阶函数:

public static <T> T retry5Times(ThrowingSupplier<T, IOException> supplier) {
for(int i = 0; i < 5; i++) {
try {
return supplier.get();
} catch (IOException e) {
LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
}
}
return null;
}

其中 ThrowingSupplier 是:

@FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
T get() throws E;
}

并以这种方式使用它:

public Document getHtml(String url) {
return retry5Times(() -> Jsoup.connect(url).get());
}

关于java - 在不同的函数中使用相同的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58623808/

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