![](/img/trans.png)
[英]spring boot microservice framework how to call another microservice from one microservice
[英]Concurrently call several Spring microservice URLs
我有一個 Spring 引導應用程序,它將使用GET
方法調用多個微服務 URL。 這些微服務 URL 端點都實現為@RestController
。 他們不返回Flux
或Mono
。
我需要我的應用程序來捕獲哪些 URL沒有返回 2xx HTTP 狀態。
我目前正在使用以下代碼來執行此操作:
List<String> failedServiceUrls = new ArrayList<>();
for (String serviceUrl : serviceUrls.getServiceUrls()) {
try {
ResponseEntity<String> response = rest.getForEntity(serviceUrl, String.class);
if (!response.getStatusCode().is2xxSuccessful()) {
failedServiceUrls.add(serviceUrl);
}
} catch (Exception e){
failedServiceUrls.add(serviceUrl);
}
}
// all checks are complete so send email with the failedServiceUrls.
mail.sendEmail("Service Check Complete", failedServiceUrls);
}
問題是每個 URL 調用響應緩慢,我必須等待一個 URL 調用完成,然后再進行下一個調用。
如何更改此設置以同時進行 URL 調用? 在所有調用完成后,我需要發送一個 email ,其中包含應在failedServiceUrls
中收集的任何錯誤 URL。
更新
我將上面的帖子修改為 state,我只想同時進行通話。 我不在乎rest.getForEntity
調用塊。
在您的代碼中使用執行器服務,您可以通過這種方式並行調用所有微服務:
// synchronised it as per Maciej's comment:
failedServiceUrls = Collections.synchronizedList(failedServiceUrls);
ExecutorService executorService = Executors.newFixedThreadPool(serviceUrls.getServiceUrls().size());
List<Callable<String>> runnables = new ArrayList<>().stream().map(o -> new Callable<String>() {
@Override
public String call() throws Exception {
ResponseEntity<String> response = rest.getForEntity(serviceUrl, String.class);
// do something with the response
if (!response.getStatusCode().is2xxSuccessful()) {
failedServiceUrls.add(serviceUrl);
}
return response.getBody();
}
}).collect(toList());
List<Future<String>> result = executorService.invokeAll(runnables);
for(Future f : result) {
String resultFromService = f.get(); // blocker, it will wait until the execution is over
}
如果您只想同時進行調用並且您不關心阻塞線程,您可以:
Mono#fromCallable
包裝阻塞服務調用Flux#fromIterable
將serviceUrls.getServiceUrls()
轉換為反應式 streamFlux#filterWhen
使用 2 中的 Flux 和 1 中的異步服務調用同時調用和過濾失敗的服務。Flux#collectList
等待所有調用完成並發送 email subscribe
中的 URL 無效void sendFailedUrls() {
Flux.fromIterable(erviceUrls.getServiceUrls())
.filterWhen(url -> responseFailed(url))
.collectList()
.subscribe(failedURls -> mail.sendEmail("Service Check Complete", failedURls));
}
Mono<Boolean> responseFailed(String url) {
return Mono.fromCallable(() -> rest.getForEntity(url, String.class))
.map(response -> !response.getStatusCode().is2xxSuccessful())
.subscribeOn(Schedulers.boundedElastic());
}
使用 Reactor 阻塞調用
由於底層服務調用是阻塞的,它應該在專用線程池上執行。 如果要實現完全並發,這個線程池的大小應該等於並發調用的數量。 這就是為什么我們需要.subscribeOn(Schedulers.boundedElastic())
請參閱: https://projectreactor.io/docs/core/release/reference/#faq.wrap-blocking
使用 WebClient 的更好解決方案
但是請注意,在使用 reactor 和 spring webflux 時應避免阻塞調用。 正確的方法是用 Spring 5 中的WebClient
替換RestTemplate
,這是完全非阻塞的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.