Creating Asynchronous Methods in Spring Boot

Posted By : Saurabh Shukla | 23-Dec-2020

What you need to begin

  • A favorite text editor or IDE (like STS or IntelliJ IDEA)
  • About 15-20 minutes
  • JDK 1.8 or later
  • Maven 3.2 

 

Annotation that needs to be used

  • @EnableAsync
  • @Async

    You need to create a maven a Spring Starter Project with the following dependencies pom.xml  

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
    
    <groupId>org.springframework.boot</groupId>
    
    <artifactId>spring-boot-starter-parent</artifactId>
    
    <version>2.1.9.RELEASE</version>
    
    <relativePath/> <!-- lookup parent from repository -->
    
    </parent>
    
    <groupId>com.async</groupId>
    
    <artifactId>AsyncSpringBoot</artifactId>
    
    <version>0.0.1-SNAPSHOT</version>
    
    <name>AsyncSpringBoot</name>
    
    <description>Demo project for Spring Boot</description>
    
    
    <properties>
    
    <java.version>1.8</java.version>
    
    </properties>
    
    
    <dependencies>
    
    <dependency>
    
    <groupId>org.springframework.boot</groupId>
    
    <artifactId>spring-boot-starter-web</artifactId>
    
    </dependency>
    
    
    <dependency>
    
    <groupId>org.springframework.boot</groupId>
    
    <artifactId>spring-boot-starter-test</artifactId>
    
    <scope>test</scope>
    
    </dependency>
    
    </dependencies>
    
    
    <build>
    
    <plugins>
    
    <plugin>
    
    <groupId>org.springframework.boot</groupId>
    
    <artifactId>spring-boot-maven-plugin</artifactId>
    
    </plugin>
    
    </plugins>
    
    </build>
    
    </project>
    

    Enabling Async Support

     

Next, add @EnableAsync annotation to spring boot application method  to run async method  like bellow 

AsyncSpringBootApplication.java

 

Also Read: Firebase CRUD operation using spring boot

 

  import org.springframework.boot.SpringApplication;

     import org.springframework.boot.autoconfigure.SpringBootApplication;

     import org.springframework.scheduling.annotation.EnableAsync;



     @SpringBootApplication

     @EnableAsync

     public class AsyncSpringBootApplication {

         public static void main(String[] args) {

             SpringApplication.run(AsyncSpringBootApplication.class, args);

         }

    }

@EnableAsync enables Spring’s ability to run Asynchronous methods in a background thread pool.

Creating the Configuration

Create a Configuration class by extending AsyncConfigurerSupport class and overriding getAsyncExecutor() with Executor return type. 

package com.async.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.annotation.AsyncConfigurerSupport;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;



@Configuration

public class AsyncConfig extends AsyncConfigurerSupport {

    @Autowired

    private AsyncExceptionHandler asyncExceptionHandler;



    @Override

    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

        taskExecutor.setCorePoolSize(5);

        taskExecutor.setMaxPoolSize(10);

        taskExecutor.setQueueCapacity(500);

        taskExecutor.setThreadNamePrefix("Async-example-thread-");

        taskExecutor.initialize();

        return taskExecutor;

    }


    @Override

 public AsyncUncaughtExceptionHandler 

       getAsyncUncaughtExceptionHandler() {

         return asyncExceptionHandler;

       }

}

Create AsyncExceptionHandler

To handle the exception which is occurred execution of the asynchronous methods.

package com.async.config;



import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

import java.util.Arrays;



@Component

public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Override

    public void handleUncaughtException(Throwable ex, Method method, Object... args) {

        System.out.println("Method Name" + method.getName()

                + "---" + Arrays.toString(args) + "----"

                + "error Message: " + ex.getMessage());

    }

}

Creating the Service

Next, We need to create a Service and create a method that will use to send messages with @Async annotation. We will use a simple RestTemplate to hit a GET API and get results asynchronously. 

NotificationService.java

package com.async.service;



import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;



@Service

public class NotificationService {

    @Async

    public void sendTextMessage(String mobile) {

System.out.println(" send text message : " + Thread.currentThread().getName())

    }

}

Creating the Controller

Next,  create a controller  to call user Notification  API 

 NotificationController.java

 

Also Read: Spring Boot Application Configured As Eureka Server

 

package com.async.controller;

import com.async.service.NotificationService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;



@RestController

public class NotificationController {

    @Autowired

    private NotificationService notificationService;


    @GetMapping("/send")

    public String sendMessage(@RequestParam String mobile) {

        notificationService.sendTextMessage(mobile);

        return "message sent successfully!!! : " + Thread.currentThread().getName();

    }

}

 

We are a 360-degree software development company that provides cross-platform SaaS app development services to address varied software project requirements. We have an experienced team of Java, PHP, and Python developers who use advanced frameworks, tools, and SDKs to build scalable web and mobile applications with custom features. For more detail, reach us out at [email protected].

 

About Author

Author Image
Saurabh Shukla

Saurabh Shukla is a software developer having key skills in Grails and J2EE. His hobbies are playing chess and learning new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..