【发布时间】:2019-05-14 09:43:51
【问题描述】:
我有两个端点:/parent 和 /child/{parentId}
我需要返回所有Child的列表
public class Parent {
private long id;
private Child child;
}
public class Child {
private long childId;
private String someAttribute;
}
但是,调用/child/{parentId} 很慢,所以我尝试这样做:
- 调用
/parent获取100条父数据,使用异步RestTemplate - 对于每个父数据,请致电
/child/{parentId}获取详细信息 - 将
/child/{parentId}的结果调用添加到resultList中 - 当 100 次调用
/child/{parentId}完成后,返回resultList
我使用包装类,因为大多数端点以格式返回 JSON:
{
"next": "String",
"data": [
// parent goes here
]
}
所以我把它包起来
public class ResponseWrapper<T> {
private List<T> data;
private String next;
}
我写了这段代码,但是 resultList 总是返回空元素。 实现这一目标的正确方法是什么?
public List<Child> getAllParents() {
var endpointParent = StringUtils.join(HOST, "/parent");
var resultList = new ArrayList<Child>();
var responseParent = restTemplate.exchange(endpointParent, HttpMethod.GET, httpEntity,
new ParameterizedTypeReference<ResponseWrapper<Parent>>() {
});
responseParent.getBody().getData().stream().forEach(parent -> {
var endpointChild = StringUtils.join(HOST, "/child/", parent.getId());
// async call due to slow endpoint child
webClient.get().uri(endpointChild).retrieve()
.bodyToMono(new ParameterizedTypeReference<ResponseWrapper<Child>>() {
}).map(wrapper -> wrapper.getData()).subscribe(children -> {
children.stream().forEach(child -> resultList.add(child));
});
});
return resultList;
}
【问题讨论】:
标签: spring-boot spring-webflux project-reactor