Java调用REST服务,在x个时间段内进行周期性响应
我必须调用REST端点(使用Java)来检索响应。配置是 totalTimeAvailableToCheck=15秒,NoOfAttempts=3秒,IntervaliantTests=3秒Java调用REST服务,在x个时间段内进行周期性响应,java,rest,scheduledexecutorservice,Java,Rest,Scheduledexecutorservice,我必须调用REST端点(使用Java)来检索响应。配置是 totalTimeAvailableToCheck=15秒,NoOfAttempts=3秒,IntervaliantTests=3秒 考虑这个,每3秒后调用一个端点。如果我得到了所需的响应,然后完成执行,否则每3秒继续尝试,然后进行3次尝试。所有这些在主线程上的总等待时间不应超过15秒。因为rest端点可能有自己的慢度 响应只是一个字符串(状态指示器)。因此,如果状态正在进行,请在间隔后继续检查,否则状态是否已完成/取消。将状态返回为响应
考虑这个,每3秒后调用一个端点。如果我得到了所需的响应,然后完成执行,否则每3秒继续尝试,然后进行3次尝试。所有这些在主线程上的总等待时间不应超过15秒。因为rest端点可能有自己的慢度
响应只是一个字符串(状态指示器)。因此,如果状态正在进行,请在间隔后继续检查,否则状态是否已完成/取消。将状态返回为响应 编辑:使用ScheduleEexcutorService是更好的方法吗?或者提供这种开箱即用的框架 编辑:我的第一次尝试是使用while(true)
,但它会有缺陷
while(attemptCount > noOfAttempts) {
sleep(3seconds);
String result = restService.get();
if(result == in progress) noOfAttempts ++
else return mapResponse(result);
}
throw timeOutException("timeout")
- 这种逻辑的缺陷在于rest服务调用需要很长时间
executorService executorService=Executors.newSingleThreadExecutors();
未来任务状态=executorService.submit(()->{
int nootfattempts=0;
while(attemptCount>noOfAttempts){
睡眠(间歇试验);
字符串结果=restService.get();
如果(结果==进行中)为空++
否则返回结果;
}
抛出timeOutException(“timeout”)//或穷举尝试异常
});
试一试{
字符串状态=taskStatus.get(totalTimeAvailableToCheck,TimeUnit.Seconds);
返回mapStatus(状态);
}捕捉(中断异常e){
抛出timeOutException(“超时”)
}
您的问题到底是什么?是的,很抱歉不清楚。我在想,如果我使用ScheduleExecutorService,或者是否有现成的框架解决方案可以使用
ExecutorrService executorService = Executors.newSingleThreadExecutors();
Future<String> taskStatus = executorService.submit( () -> {
int noOfAttempts = 0;
while(attemptCount > noOfAttempts) {
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")
}