In this tutorial we will see how to create an asynchronous REST service endpoint using Spring boot application.
Asynchronous service works in a way that it will not block the client request and do the processing in separate thread. When work is complete the response returned to the client so our service will be able to handle more client requests at the same time, compare to synchronous processing model.
Let's understand how it is working in synchronous mode. In such server/client application at server side it has a pool of threads which are serving the request. If a request received by a thread then it will be blocked until it send the response back to client. In this case if processing doesn't take much time it will be able to process it quickly and accept other client requests but there could be one situation when all threads are busy and not able to accept the new client requests.
To overcome of such problems, asynchronous processing model introduced for REST services. In this processing model, after receiving the request from client it creates a separate worker thread to process the request and request thread becomes available to accept the more requests. Worker thread send the response back to client once it completes the processing.
Here we are going to see how to implement asynchronous REST service using Spring boot application, however now JAX-RS 2 also supports asynchronous communication but Spring uses it's own API for REST implementation.
It comes with various constructor implementation using which we can supply timeout and custom executors also. Also it provides some callback methods which can be executed on success, error or timeout events for this task. See the below code of our REST service.
URL: http://localhost:8080/hello?name=Akshay
Response:
URL: http://localhost:8080/hello?name=timeout
Response:
URL: http://localhost:8080/hello?name=error
Response:
Asynchronous service works in a way that it will not block the client request and do the processing in separate thread. When work is complete the response returned to the client so our service will be able to handle more client requests at the same time, compare to synchronous processing model.
Let's understand how it is working in synchronous mode. In such server/client application at server side it has a pool of threads which are serving the request. If a request received by a thread then it will be blocked until it send the response back to client. In this case if processing doesn't take much time it will be able to process it quickly and accept other client requests but there could be one situation when all threads are busy and not able to accept the new client requests.
To overcome of such problems, asynchronous processing model introduced for REST services. In this processing model, after receiving the request from client it creates a separate worker thread to process the request and request thread becomes available to accept the more requests. Worker thread send the response back to client once it completes the processing.
Here we are going to see how to implement asynchronous REST service using Spring boot application, however now JAX-RS 2 also supports asynchronous communication but Spring uses it's own API for REST implementation.
Maven dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
@EnableAsync
First we need to add this annotation on any configuration class or spring boot main class. Configuration classes are those who have the annotation @Configuration. We need this annotation to enable the asynchronous execution capabilities of Spring. Once async is enable Spring will look for the task executor bean and if it is not found then Spring will use SimpleAsyncTaskExecutor to execute the tasks asynchronously.@EnableAsync public class SpringBootTutorialApplicationTask executor is optional but may be useful depending on our requirement as we can tune it as per need. I am putting it here for your reference but it's your choice whether you want to customize it or not. We need to use the @EnableAsync annotation and implement the interface AsyncConfigurer. Below is code for the task executor implementation.
@EnableAsync public class SpringBootTutorialApplication implements AsyncConfigurer{ public static void main(String[] args) { SpringApplication.run(SpringBootTutorialApplication.class, args); } @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(20); executor.setQueueCapacity(10); executor.setThreadNamePrefix("DemoExecutor-"); executor.initialize(); return executor; } }
Async REST service
Now we need to create the REST service which execute asynchronously using the WebAsyncTask. WebAsyncTask is a Spring class which needs Callable task to get initialized and then this instance we need to return from our REST endpoint.It comes with various constructor implementation using which we can supply timeout and custom executors also. Also it provides some callback methods which can be executed on success, error or timeout events for this task. See the below code of our REST service.
@RestController public class AsyncRestController { @GetMapping("/hello") public WebAsyncTaskIn above code we have one REST endpoint "/hello" which accepts a name returns the response after 2 seconds. We are returning an instance of WebAsyncTask which is configured to be timeout after 4 seconds. We will test here below 3 scenarios to see the different response for each of the above callback methods.sayHello(@RequestParam(defaultValue="Demo user") String name){ System.out.println("service start..."); WebAsyncTask task = new WebAsyncTask (4000, () -> { System.out.println("task execution start..."); int waitSeconds = 2; if("timeout".equals(name)) { waitSeconds = 5; } Thread.sleep(waitSeconds * 1000); if("error".equals(name)) { throw new RuntimeException("Manual exception at runtime"); } System.out.println("task execution end..."); return "Welcome "+name+"!"; }); task.onTimeout(()->{ System.out.println("onTimeout..."); return "Request timed out..."; }); task.onError(()->{ System.out.println("onError..."); return "Some error occurred..."; }); task.onCompletion(()->{ System.out.println("onCompletion..."); }); System.out.println("service end..."); return task; } }
1. Success response
In this case it returns response in 2 seconds and "onCompletion" callback method is executed. Here in console output we can see that our logic is executed asynchronously and response has return once it was ready to send after 2 seconds.URL: http://localhost:8080/hello?name=Akshay
Response:
Welcome Akshay!Console output:
service start... service end... task execution start... task execution end... onCompletion...
2. Time out response
Since service is not able to send the response before configured timeout, it will time out and callback method for "onTimout" will be executed. In the console output it shows that even though timeout has occurred, it has executed the callback method for onTimout as well as onCompletion.URL: http://localhost:8080/hello?name=timeout
Response:
Request timed out...Console output:
service start... service end... task execution start... onTimeout... onCompletion...
3. Error response
In this case, we generate the manual exception which results in the execution of "onError" callback method. By seeing the console output it is clear that it throws exception and executes two callback methods "onError" and "onCompletion".URL: http://localhost:8080/hello?name=error
Response:
Returns Spring's error page.Console output:
service start... service end... task execution start... java.lang.RuntimeException: Manual exception at runtime .... onError... onCompletion...
Thanks for posting such useful information. You have done a great job.
ReplyDeletePHP Training in Chennai | Certification | Online Training Course | Machine Learning Training in Chennai | Certification | Online Training Course | iOT Training in Chennai | Certification | Online Training Course | Blockchain Training in Chennai | Certification | Online Training Course | Open Stack Training in Chennai |
Certification | Online Training Course
I have read your excellent post. This is a great job. I have enjoyed reading your post first time. I want to say thanks for this post. Thank you…ufabet168
ReplyDeletethis greatful informative of us. thanks for sharing. Kinemaster Gold
ReplyDeleteThanks for this useful blog, keep sharing your thoughts...
ReplyDeleteUnix Program
Unix Applications
Download Mod Games APK, A2Z APK, Mod APK, Mod APPS, Mod Games, Android Application, Free Android App, Android Apps, Android APK
ReplyDelete.
Great post tthanks
ReplyDeleteLoved readiing this thank you
ReplyDelete