java – 从异步休息模板spring返回值
作者:互联网
我正在使用spring创建一个异步休息调用
@GetMapping(path = "/testingAsync")
public String value() throws ExecutionException, InterruptedException, TimeoutException {
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
String baseUrl = "https://api.github.com/users/XXX";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String value = "";
HttpEntity entity = new HttpEntity("parameters", requestHeaders);
ListenableFuture<ResponseEntity<User>> futureEntity = restTemplate.getForEntity(baseUrl, User.class);
futureEntity.addCallback(new ListenableFutureCallback<ResponseEntity<User>>() {
@Override
public void onSuccess(ResponseEntity<User> result) {
System.out.println(result.getBody().getName());
// instead of this how can i return the value to the user ?
}
@Override
public void onFailure(Throwable ex) {
}
});
return "DONE"; // instead of done i want to return value to the user comming from the rest call
}
有没有什么办法可以将ListenableFuture转换为使用java 8中使用的CompletableFuture?
解决方法:
你基本上可以做两件事.
>删除ListenableFutureCallback并返回ListenableFuture
>创建一个DeferredResult并在ListenableFutureCallback中设置它的值.
返回ListenableFuture
@GetMapping(path = "/testingAsync")
public ListenableFuture<ResponseEntity<User>> value() throws ExecutionException, InterruptedException, TimeoutException {
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
String baseUrl = "https://api.github.com/users/XXX";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String value = "";
HttpEntity entity = new HttpEntity("parameters", requestHeaders);
return restTemplate.getForEntity(baseUrl, User.class);
}
Spring MVC将添加一个ListenableFutureCallback本身来填充DeferredResult,最终你会得到一个User.
使用DeferredResult
如果您想要更多地控制返回的内容,可以使用DeferredResult并自己设置值.
@GetMapping(path = "/testingAsync")
public DeferredResult<String> value() throws ExecutionException, InterruptedException, TimeoutException {
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
String baseUrl = "https://api.github.com/users/XXX";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String value = "";
HttpEntity entity = new HttpEntity("parameters", requestHeaders);
final DeferredResult<String> result = new DeferredResult<>();
ListenableFuture<ResponseEntity<User>> futureEntity = restTemplate.getForEntity(baseUrl, User.class);
futureEntity.addCallback(new ListenableFutureCallback<ResponseEntity<User>>() {
@Override
public void onSuccess(ResponseEntity<User> result) {
System.out.println(result.getBody().getName());
result.setResult(result.getBody().getName());
}
@Override
public void onFailure(Throwable ex) {
result.setErrorResult(ex.getMessage());
}
});
return result;
}
标签:java,spring,rest,asynchronous,rest-client 来源: https://codeday.me/bug/20190727/1551826.html