在Spring Java中同时调用多个webservice(Calling mutiple webservice at same time in Spring Java)

编程入门 行业动态 更新时间:2024-10-25 15:22:40
在Spring Java中同时调用多个webservice(Calling mutiple webservice at same time in Spring Java)

我有一个30台服务器的列表,我必须对每台服务器进行一次REST调用才能获得它们的状态。 目前我遍历服务器列表并依次调用每个服务器的每个REST调用。 因此,在将结果返回给JSP VIEW之前,总共需要大约30秒才能获得每个服务器的响应。

我们该怎样改进这个?

I have a list of 30 servers and I have to make a REST call to each server to get their status. Currently I iterating through list of server and sequentially calling each REST call against each server. So totally it takes around 30 seconds in total to get the response from each server before returning the result to JSP VIEW.

How can we improve this?

最满意答案

您可以考虑的一个选项是Java8流,如下所示:

public void check() { List<String> endPoints = Arrays.asList("http://www.google.com", "http://www.stackoverflow.com", "inexistent"); { // this will execute the requests in parallel List<Boolean> collected = performCheckOverStream(endPoints.parallelStream()); System.out.println(collected); } { // this will execute the requests in serial List<Boolean> collected = performCheckOverStream(endPoints.stream()); System.out.println(collected); } } private List<Boolean> performCheckOverStream(Stream<String> stream) { List<Boolean> collected = stream.map(new Function<String, Boolean>() { @Override public Boolean apply(String t) { // do what you need here } }).collect(Collectors.toList()); return collected; }

使用Spring,您可以使用@Async注释方法,或者甚至使用AsyncRestTemplate,在这两种情况下您都会收到Future<?> 。 一个很好的@Async可以在这里找到,也可以在这里找到AsyncRestTemplate 。

One option you could consider is the Java8 streams like:

public void check() { List<String> endPoints = Arrays.asList("http://www.google.com", "http://www.stackoverflow.com", "inexistent"); { // this will execute the requests in parallel List<Boolean> collected = performCheckOverStream(endPoints.parallelStream()); System.out.println(collected); } { // this will execute the requests in serial List<Boolean> collected = performCheckOverStream(endPoints.stream()); System.out.println(collected); } } private List<Boolean> performCheckOverStream(Stream<String> stream) { List<Boolean> collected = stream.map(new Function<String, Boolean>() { @Override public Boolean apply(String t) { // do what you need here } }).collect(Collectors.toList()); return collected; }

Using Spring you could either use a @Async annotated method or even use the AsyncRestTemplate, in both cases you will receive a Future<?>. A nice introduction to @Async can be found here and to the AsyncRestTemplate here.

更多推荐

本文发布于:2023-07-31 01:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   Java   Spring   webservice   time

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!