Java – return value from asynchronous rest template spring

I'm using spring to create an asynchronous rest call

@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 
}

Is there any way to convert the listenablefuture to the completable future used in Java 8?

Solution

You can basically do two things

>Delete the listenablefuturecallback and return to listenablefuture > create a deferredresult and set its value in the listenablefuturecallback

Return to listenablefuture

@GetMapping(path = "/testingAsync")
public ListenableFuture<ResponseEntity<User>> value() throws ExecutionException,requestHeaders);
    return restTemplate.getForEntity(baseUrl,User.class);
}

Spring MVC will add a listenablefuturecallback itself to fill in the deferredresult, and eventually you will get a user

Use deferredresult

If you want more control over what is returned, you can use deferredresult and set the value yourself

@GetMapping(path = "/testingAsync")
public DeferredResult<String> value() throws ExecutionException,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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>