我有30台服务器的列表,我必须对每个服务器进行休息才能获得其状态。当前,我通过服务器列表进行迭代,然后对每个服务器依次调用每个REST调用。因此,总共需要大约30秒钟的时间才能从每个服务器中获取响应,然后再将结果返回JSP视图。
我们如何改进?
您可以考虑的一个选项是:
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
。
您可以通过Theapool这样做,而线程计数为API调用计数。
public void REST_Thread_executor(int Thread_count, ArrayList URLS) {
ExecutorService executor = Executors.newFixedThreadPool(Thread_count);
for (int i = 0; i < Thread_count; i++) {
String URL = URLS.get(i).toString();
Runnable worker = new MyRunnable(URL);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
public String restAPICALL(URL) {
GET or POST or PUT or DELETE
}
public static class MyRunnable implements Runnable {
private final String URL;
RESTThreadExecutor restThreadExecutor = new RESTThreadExecutor();
MyRunnable(String URL) {
this.URL = URL;
}
@Override
public void run() {
restThreadExecutor.restAPICALL(URL);
}
}
您可以使用Java 9中的完整图接口。或在应用程序上启用@enableasync和方法,使用@Async,将返回您的接口未来。两者都是异步流。