Skip to main content

Asynchronous REST service implementation in Spring boot

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.
synchronous communication

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.
asynchronous communication

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 SpringBootTutorialApplication
Task 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 WebAsyncTask 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;
    }
}
In 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.

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...

Comments

Popular Posts

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check.
havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false.matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment.name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"}prefix - It can be use when you want to apply some prefix to all prop…

Entity to DTO conversion in Java using Jackson

It's very common to have the DTO class for a given entity in any application. When persisting data, we use entity objects and when we need to provide the data to end user/application we use DTO class. Due to this we may need to have similar properties on DTO class as we have in our Entity class and to share the data we populate DTO objects using entity objects. To do this we may need to call getter on entity and then setter on DTO for the same data which increases number of code line. Also if number of DTOs are high then we need to write lot of code to just get and set the values or vice-versa.
To overcome this problem we are going to use Jackson API and will see how to do it with minimal code only.
Maven dependency <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> Entity class Below is our ent…

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database.
Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application.
Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below.
brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere.
Open user's bash profile:
vi ~/.bash_profile Add below lines:
export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS="-L/usr/lo…