java - 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")
- 这种逻辑的缺陷是如果休息服务调用需要很长时间。
解决方案
经过一番研究,一个简单的方法。
为了解释这种方法,只需使用 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
}
推荐阅读
- python - SageMaker 脚本模式 + 管道模式
- excel - 不引用excel表上的列
- autodesk-forge - 为什么文本标记大小因缩放而异?
- sql - 使用 CalendarTable SQL Server 2008 计算 NETWORKDAYS
- flask - Psycopg2 和 Flask - 将连接绑定到 before_request 和 teardown_appcontext
- zendesk - 页面重新加载后如何触发 zendesk Web 小部件?
- android - 表 users_data 没有名为的列
- sql - 有没有更好的方法来拆分简单更新的工作?
- java - 删除 ArrayList 中大于 x 的数字
- reactjs - 模拟表单提交时无法读取属性“值”