首页 > 解决方案 > Java 在 x 时间段内调用 REST 服务,以定期间隔进行响应

问题描述

我必须调用 REST 端点(使用 Java)来检索响应。配置是

totalTimeAvailableToCheck = 15 秒,NoOfAttempts = 3,intervalInAttempts = 3 秒。

因此,请考虑每 3 秒后将调用一个端点。如果我得到所需的响应,则完成执行,否则每 3 秒后继续尝试接下来的 3 次尝试。主线程上所有这些的总等待时间不应超过 15 秒。由于休息端点可能有其自身的缓慢性。

响应只是一个字符串(状态指示器)。因此,如果状态为 IN PROGRESS,则在间隔后继续检查,否则如果状态为 DONE/CANCELLED。返回状态作为响应。

编辑:为这个更好的方法使用 ScheduleEexcutorService 吗?或者任何提供这个开箱即用的框架?

编辑:我的第一次尝试是 withwhile(true)但它会有缺陷

while(attemptCount > noOfAttempts) {
    sleep(3seconds);
    String result = restService.get();
    if(result == in progress) noOfAttempts ++
    else return mapResponse(result);
}
throw timeOutException("timeout")

标签: javarestscheduledexecutorservice

解决方案


经过一番研究,一个简单的方法。

为了解释这种方法,只需使用 future.get(15 ,TimeUnit.seconds) 在单个线程中循环调用其余服务等待 15 秒(根据我的要求,未来阻塞不是问题)。

ExecutorrService executorService = Executors.newSingleThreadExecutors();
Future<String> taskStatus = executorService.submit( () -> {
int noOfAttempts = 0;
while(attemptCount > noOfAttempts && !Thread.interrupted()) {
    sleep(intervalInAttempts);
    String result = restService.get();
    if(result == in progress) noOfAttempts ++
    else return result;
}
throw timeOutException("timeout") // or exhaust attempt exception

});

try {
 String status = taskStatus.get(totalTimeAvailableToCheck, TimeUnit.Seconds);
return mapStatus(status);
} catch(InterruptedException e) {
throw timeOutException("timeout")
}catch(TimeOutException e) {
taskStatus.cancel(true); // to interrupt the sub tasks
}

推荐阅读