我正在尝试初始化对象直到成功。该代码工作正常,但不适用于第一个实例/迭代。有没有办法在 while 循环中初始化对象?
V1NamespaceList listOfns = null;
try {
listOfns = api.listNamespace(null, true, null, null, null, null, null, null, null, null);
} catch (Exception e) {
System.out.println("Something went wrong while fetching namespace list. Trying again ");
while (listOfns != null)
{
listOfns = api.listNamespace(null, true, null, null, null, null, null, null, null, null);
}
}
我的目标是尝试直到
listOfns
对象初始化成功。我怎样才能实现这一目标?
我建议在程序中添加重试次数。如果程序继续失败,您应该排除出现问题的原因。除非真的有特殊需要。
V1NamespaceList listOfNs = null;
int retryCount = 0;
final int MAX_RETRIES = 5;
while (retryCount < MAX_RETRIES) {
try {
listOfNs = api.listNamespace(null, true, null, null, null, null,
null, null, null, null);
if (listOfNs != null) {
break;
}
} catch (Exception e) {
System.out.println("Something went wrong while fetching namespace list. Trying again. Retry #" + (retryCount + 1));
}
retryCount++;
// can sleep for a while
//try {
// Thread.sleep(1000);
//} catch (InterruptedException ie) {
// Thread.currentThread().interrupt();
//}
}
if (listOfNs == null) {
System.out.println("Failed to fetch namespace list after " + MAX_RETRIES + " attempts.");
// TODO
}
这就是 spring-retry 可以发挥作用的地方。只需根据您的喜好配置 retryTemplate 即可。
RetryTemplate retryTemplate = RetryTemplate.builder().infiniteRetry()
.exponentialBackoff(Duration.ofMillis(100), 2, Duration.ofSeconds(5)).build();
String listOfNs = retryTemplate.execute(context -> {
log.info("RetryNo: {}", context.getRetryCount());
// return api.listNamespace(....)
return "Hello World!";
});
log.info("Retry: {}", listOfNs);