[英]Consuming Rest Service the functional way
所以我很好奇如何使用java8流API更好地重寫以下代碼。
public static List<FlightInfo> getResults(String origin,List<String> destinations) {
final String uri = "https://api.searchflight.com/;
List<FlightInfo> results = new LinkedList<FlightInfo>();
for(String destination:destinations) {
RestTemplate restTemplate = new RestTemplate();
String params = getParams(origin,destination);
FlightInfo result = restTemplate.postForObject(uri+params,FlightInfo.class);
results.add(result);
}
return results;
}
在完成此方法之后,我正在做它正在做的事情並且我收到了FLightInfo對象的列表,我將它轉換為流並將對其進行各種轉換(分組依此類推)。 現在很明顯這是一個長期運行的操作。 此外,它實際上將多個休息調用組合到Web服務,所以我已經擁有了在上次調用時獲得的大部分數據,但是在整個方法返回之前我不會開始處理它。
有沒有辦法做更多反應性的事情? 我可以立即返回一個流並對該流進行操作,因為它來自管道或者這有點太多了嗎? 如何在Java 8中完成。那
那么這一切都取決於你何時需要結果。 如果你希望它是連續的,下面的它仍然是一個體面的方式,因為它的懶惰。 但它會在終端操作(例如collect
期間)沸騰。
public static Stream<FlightInfo> getResults(String origin,List<String> destinations) {
final String uri = "https://api.searchflight.com/";
return destinations.stream().map(destination -> {
RestTemplate restTemplate = new RestTemplate();
String params = getParams(origin,destination);
FlightInfo result = restTemplate.postForObject(uri+params,FlightInfo.class);
return result;
})
}
或者如果可以的話,我會使用destinations.stream().parallel()
。 在大多數情況下,這是一個合理的結果。 但是,直到你為它調用終端操作時,它仍然不會開始並行處理它。 這絕對有道理。
但在我看來,你希望生產者 - 消費者類型的東西。 對於:
public static CompletableFuture<List<FlightInfo>> getResults(String origin,List<String> destinations) {
final String uri = "https://api.searchflight.com/";
List<CompletableFuture<FlightInfo>> collect = destinations
.stream()
.map(destination -> CompletableFuture.supplyAsync(() -> {
RestTemplate restTemplate = new RestTemplate();
String params = getParams(origin,destination);
FlightInfo result = restTemplate.postForObject(uri+params,FlightInfo.class);
return result;
})).collect(Collectors.toList());
return sequence(collect); //line-1
}
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> com) {
return CompletableFuture.allOf(com.toArray(new CompletableFuture[com.size()]))
.thenApply(v -> com.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
);
}
為簡單起見 ,在line-1
您只需返回collect
而不是sequence(collect)
。 然后,您可以遍歷列表以獲取每個值。
但是對於sequence
,您需要擔心一個CompletableFuture對象,如果完成,您可以立即檢查值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.