我正在后端(垂直代码)从数据库中读取数据,并且每一行都有一个url,我将在该URL上对状态字段执行“ GET” http请求,以作为响应,我将其存储回数据库并发送到UI。
CreateRequests方法发出http请求。我想同时执行。
List<Future> toComplete=new ArrayList<>();
Vertx vertx = Vertx.vertx();int i;
for(i=0;i<requestsListInDept.size();i++)
{
String reqtype = requestsListInDept.getString(i);
JsonObject requestProperties = dataReader.getRequestProperties(dept,reqtype);
toComplete.add(Future.future());
int currrent=i;
vertx.executeBlocking(future->{
System.out.println("calling for ");
String individualResponse = accReq.createRequests(requestContext,reqtype,empid,requestProperties);
toComplete.get(currrent).complete(individualResponse);
future.complete(individualResponse);
},false,res->{
JsonArray obj=new JsonArray( (res.result()).toString() );
for(int index=0;index<obj.size();index++)
{
JsonObject requestResponse=obj.getJsonObject(index);
response.add(requestResponse);
}
toComplete.get(currrent).complete(res.result());
});
}
CompositeFuture.all(toComplete).setHandler(e -> {
String collect = e.result()
.list()
.stream()
.map(Object::toString)
.collect(Collectors.joining(" ------- "));
System.out.println(collect);
});
return ;
如何有效地进行并发的get调用并合并响应(我将发送到UI的响应)并将它们存储回数据库
我正在循环所有URL并在循环中进行get请求。如果有大数据,我将得到Timeout(很明显)
答案 0 :(得分:0)
Vert.x使用反应堆模式,因此使用该模式而不是多线程和executeBlocking可以获得类似的结果。仅在没有方法支持该模式(意味着没有异步方法)时才建议在Vert.x中使用多线程和阻塞调用。
也许这个例子可以帮助您
public void doCall() {
List<Future> toComplete = new ArrayList<>();
WebClientOptions options = new WebClientOptions().setSsl(true);
WebClient webClient = WebClient.create(Vertx.vertx(), options);
IntStream.range(0, 15).forEach(counter -> {
toComplete.add(Future.future());
int current = counter;
webClient.get(443, "google.com", "/")
.send(httpResponseAsyncResult -> {
String googleResult = httpResponseAsyncResult.result().bodyAsString();
toComplete.get(current).complete(googleResult);
});
System.out.println("Calling google: times " + ++counter);
});
CompositeFuture.all(toComplete).setHandler(e -> {
String collect = e.result()
.list()
.stream()
.map(Object::toString)
.collect(Collectors.joining(" ------- "));
System.out.println(collect);
});
}
希望这会有所帮助