如何使用Spring Boot WebClient收集分页的API响应?
作者:互联网
我有一个来自URL的分页响应,我想继续点击从上一个响应中获得的下一个页面URL,并继续收集项目,直到我的响应中没有“ nextPage” URL.如何使用WebFlux的Spring Boot WebClient以无阻碍的方式以反应方式实现此目标?
Request1:
GET /items
response:
{
items: [...]
nextPage: "/items?page=2"
}
Request2:
GET /items?page=2
response:
{
items: [...]
nextPage: "/items?page=3"
}
Request3:
GET /items?page=3
response:
{
items: [...]
nextPage: null
}
在这里,我创建了模拟网址
https://karthikdivi.com/apps/paginatedReviews/withNextPageTokens/items
https://karthikdivi.com/apps/paginatedReviews/withNextPageTokens/items?page=2
https://karthikdivi.com/apps/paginatedReviews/withNextPageTokens/items?page=3
如何以无障碍方式从上述响应中提取所有项目?
解决方法:
使用扩展,可以实现这一点.
根据您提供的模拟网址.
public Mono<List<Item>> getItems() {
String url = "https://karthikdivi.com/apps/paginatedReviews/withNextPageTokens/items";
return fetchItems(url).expand(response -> {
if (response.getNextPage() == null) {
return Mono.empty();
}
return fetchItems(response.getNextPage());
}).flatMap(response -> Flux.fromIterable(response.getItems())).collectList();
}
private Mono<Response> fetchItems(String url) {
return client.get().uri(url).retrieve()
.bodyToMono(Response.class);
}
标签:project-reactor,spring-webflux,spring-boot,reactive-programming,spring 来源: https://codeday.me/bug/20191024/1924251.html