
DeepSeek R1 × 飛書多維表格賦能教育領域
List < Rating > ratings = new ArrayList < > ();
ratings.add(new Rating("1234", 4));
ratings.add(new Rating("5678", 5));
為了獲取電影信息,我們將使用REST模板調用電影信息服務。
為了簡化演示,我們暫時硬編碼評分數據。在實際應用中,這些數據將通過API獲取。
public class Rating {
private String movieId;
private int rating;
public Rating(String movieId, int rating) {
this.movieId = movieId;
this.rating = rating;
}
// Getters and setters
}
創建一個電影信息模型類,用于存儲電影詳細信息。
public class Movie {
private String movieId;
private String name;
public Movie(String movieId, String name) {
this.movieId = movieId;
this.name = name;
}
// Getters and setters
}
對于每個評分,我們將循環調用電影信息服務獲取電影詳細信息。
private List < CatalogItem > getCatalogItems(List < Rating > ratings) {
return ratings.stream()
.map(this::getCatalogItem)
.collect(Collectors.toList());
}
private CatalogItem getCatalogItem(Rating rating) {
Movie movie = restTemplate.getForObject(
"http://localhost:8080/movies/" + rating.getMovieId(),
Movie.class
);
return new CatalogItem(
movie.getName(),
"Test Description",
rating.getRating()
);
}
在代碼中創建REST模板實例,用于發送HTTP請求并接收響應。
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
使用REST模板的getForObject
方法調用API,并將響應轉換為電影信息對象。
Movie movie = restTemplate.getForObject(
"http://localhost:8080/movies/" + rating.getMovieId(),
Movie.class
);
確保電影信息類中有空構造函數,以便正確反序列化。
public class Movie {
private String movieId;
private String name;
public Movie() {}
public Movie(String movieId, String name) {
this.movieId = movieId;
this.name = name;
}
// Getters and setters
}
將獲取的電影信息整合到目錄項中,并返回給用戶。
public class CatalogItem {
private String name;
private String description;
private int rating;
public CatalogItem(String name, String description, int rating) {
this.name = name;
this.description = description;
this.rating = rating;
}
// Getters and setters
}
討論如何使用異步方式調用API,以提高應用的性能和響應速度。
private List < CatalogItem > getCatalogItemsAsync(List < Rating > ratings) {
List < CompletableFuture < CatalogItem >> futures = ratings.stream()
.map(this::getCatalogItemAsync)
.collect(Collectors.toList());
return futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
}
private CompletableFuture < CatalogItem > getCatalogItemAsync(Rating rating) {
return CompletableFuture.supplyAsync(() - > {
Movie movie = restTemplate.getForObject(
"http://localhost:8080/movies/" + rating.getMovieId(),
Movie.class
);
return new CatalogItem(
movie.getName(),
"Test Description",
rating.getRating()
);
});
}
處理API調用過程中可能出現的錯誤,確保應用的健壯性和可靠性。
private CatalogItem getCatalogItemWithErrorHandling(Rating rating) {
try {
Movie movie = restTemplate.getForObject(
"http://localhost:8080/movies/" + rating.getMovieId(),
Movie.class
);
return new CatalogItem(
movie.getName(),
"Test Description",
rating.getRating()
);
} catch (RestClientException e) {
// Handle error
return new CatalogItem("Movie not found", "Description", 0);
}
}
通過本教程,我們學習了如何在微服務架構中調用和整合不同服務的API。希望這些內容對你有所幫助!
原文引自YouTube視頻:https://www.youtube.com/watch?v=WPKv8NA-ZhE