Reputation: 1023
I have a small Spring Boot app waiting for REST calls to start an async job. However what I'd like to do next is get results of those async jobs and store them in DB. But I don't know how to use object returned with Future asynchronically. Here is more or less what I have:
@RequestMapping("/vlan/{id}/{name}")
public void performVLANConfig(@PathVariable("id") int id, @PathVariable("name") String name) {
logger.debug("Received req");
Future<ProcessedRequest> processedRequestFuture= asyncService.processVlan(id, name);
processedRequestRepository.save(processedRequest);
}
But now it just waits for async call to end. Is there any way to let the async method live its life and after it has completed store this completition error?
Upvotes: 0
Views: 1414
Reputation: 23329
You need to attach a callback. If you using Future
then you can't attach a callback to it, assign to a ListenableFuture
instead, the service needs to return a ListenableFuture
of course.
ListenableFuture<ProcessedRequest> future = asyncService.processVlan(id, name);
future.addCallback(new ListenableFutureCallback<ProcessedRequest>() {
@Override
public void onFailure(Throwable throwable) {
// deal with it
}
@Override
public void onSuccess(ProcessedRequest processedRequest) {
processedRequestRepository.save(processedRequest);
}
});
Upvotes: 2