Asynchronous callbacks in Springboot (Part 2)
In the previous Post of asynchronous callbacks we discussed how to do asynchronous callbacks using CompletableFuture class in java.
http://thebadengineer.com/asynchronous-callbacks-in-springboot/
In this post I will share the method which I used to call different REST APIs asynchronously.For this we can use ListenableFuture.
Both ListenableFuture and CompletableFuture has an edge over Future class of Java and Java 8 ships both of them together.
More info in these links:
- https://medium.com/pramod-biligiris-blog/listenablefuture-vs-completablefuture-a-comparison-3cd76ee29d6
- https://pramodb.com/2019/11/04/how-is-google-guava-listenablefuture-better-than-java-future/
- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/concurrent/ListenableFuture.html
- https://stackoverflow.com/questions/38744943/listenablefuture-vs-completablefuture
Steps are:
- Create AsyncRestTemplate Object.
- Methods which is used to call the function is asyncRestTemplate.exchange().
- This is the most common way to call the rest api of other microservices.
//Example of exchange used HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> testMap = new HashMap<>(); testMap.put("size",10); HttpEntity<Map<String,Object>> entity = new HttpEntity<>(testMap, headers); restTemplate.exchange(uri, HttpMethod.PUT, entity, Object.class);
If someone wants to use delete , there’s one more method asyncRestTemplate.delete() which does the work.It is described below:
String someurl = "http://localhost:8082/ratingsdata"; String some2url = "http://localhost:8081/movies"; private static AsyncRestTemplate asyncRestTemplate = null; @RequestMapping("/{userId}") public void getCatalog(@PathVariable("userId") String userId) throws Exception { asyncRestTemplate = new AsyncRestTemplate(); invokeAsyncDelete(someurl); invokeAsyncDelete(some2url); } public void invokeAsyncDelete(String fullUri) throws Exception { //This will call the DELETE API of the respective URL if present ListenableFuture<?> deletedFuture = asyncRestTemplate.delete(new URI(fullUri)); deletedFuture.addCallback(new ListenableFutureCallback<Object>() { @Override public void onSuccess(Object result) { System.out.println("Success for : " + fullUri); } @Override public void onFailure(Throwable genEx) { System.out.println("Failure for:" + fullUri); } }); } /*Output:Success for : http://localhost:8081/movies Success for : http://localhost:8082/ratingsdata */
Use cases:
- If Someone wants to delete the records by calling the DELETE API of other services in database with no dependecies with each other , then we can use above method.
It is tested and it works fine..