我有一个可以说 2000 个用户 ID 的列表,我想将异步请求发送到同一台服务器,将 id 作为参数传递给WebTarget
.
系统将返回映射到 UserReport 类的 JSON。它包括一个List<User>
和大小为 1(如果找到用户)。
对于每个结果,我都想将用户保存在数据库中。有没有办法让它全部异步?即,一旦我收到响应,就向数据库发送一个 INSERT。
我发送单个请求的代码:
public UserReport runRequest(String id){
return this.webTarget.path("some_path")
.queryParam("id", id)
.request(MediaType.TEXT_PLAIN_TYPE)
.get(new GenericType<UserReport >() {});
}
最后一个问题.. 使用 Observable 还是 Future?
我终于用ExecutorService
和解决了它Future
我贴出答案:
public List<User> getAllUsers(List<String> ids) {
List<Future<UserReport>> futures = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(10);
int counterU = 0;
for (String id : ids) {
Callable<UserReport> task = () -> {
return runRequest(id);
};
futures.add(executor.submit(task));
LOGGER.info("Added Task {} for UserId {}.", counterH++, id);
}
List<User> toReturn = new ArrayList<>();
for (Future<UserReport> future : futures) {
try {
UserReport report = future.get();
if (report.getUsers() != null) {
User temp = report.getUsers().get(0);
LOGGER.info("Got details for User {}.", temp.getId());
toReturn.add(temp);
insertUserToDB(temp);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
return toReturn;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句