【发布时间】:2019-02-17 01:00:05
【问题描述】:
我正在尝试使用 Observables 并行调用 REST API。我在这方面面临一些问题。我在这里描述了问题。有人可以帮我吗?
我的用例是,我有 5 个客户 ID,我需要通过同时传递此用户 ID 来调用另一个 REST API 以获取响应。
所以我决定在这里使用 Observables 以获得更好的性能来同时访问服务。
我尝试了以下 3 个选项。但我觉得,它们都提供了相同的响应时间。我没有看到所有这些调用的响应时间有任何差异
有人能在这段代码中找出错误所在吗?我是否正确使用了 Observables?
1) Observable.from(customerIds).flatMap(customerId ->
asyncUserRetrieve(customerId)
.subscribeOn(Schedulers.io()))
.subscribe(cust -> {
custDetails.add(cust);
});
2) Observable.from(customerIds).flatMap(customerId ->
asyncUserRetrieve(customerId)
.subscribe(cust -> {
custDetails.add(cust);
});
3) for(String id : customerId) {
Customer customer = asyncUserRetrieve(id).toBlocking().single();.
custDetails.add(cust);
}
@Override
public Observable<Customer> asyncUserRetrieve(String customerId) {
final URI uri = getURL(customerId);
final Response response = httpClient.callForResponse(uri);
if (response.getHttpStatus().is2xxSuccessful()) {
Customer customer = getResponse(response, customerId);
return Observable.just(customer);
}
return Observable.just(new Customer().setError(true));
}
【问题讨论】:
标签: asynchronous java-8 rx-java microservices reactive-programming