Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 18, 2022 07:17 pm GMT

Create an asynchronous method in Spring Boot

Normally, a given program runs straight along, with only one thing happening at once. And a block of code that relies on the previous one, should wait for it to end executing, and until that happens everything is stopped from the perspective of the user.

Lets say we want to make a call to an API, knowing that the service we are calling takes too much time. So we prefer to return a response, telling that the call was made and the processing has started.

You might be wondering either the process succeeded or not, so instead of waiting for a single call to end, you can log everything and check on it later or make another service that returns the result (if you are really interested).

How to create an asynchronous method in Spring Boot

1. Enabling Async Support:

To enable asynchronous processing, with Java configuration, simply add the @EnableAsync to a configuration class:

import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableAsync;@Configuration@EnableAsyncpublic class SpringAsyncConfig {}

The enable annotation is enough, but there is more options you can add as well (like specifying the ThreadPoolTaskExecutor).

2. Making your service asynchronous:

We won't be touching the controller, so it will be something like:

@GetMapping("/do-heavy-work")    public ResponseEntity<MessageResponse> getTheWorkDone() {                //this service is called,                 //but the process does not wait for its execution to end        someService.doWorkAsynchronously();                //we return immediately ok to the client        return ResponseEntity.ok(new MessageResponse("Executing..."));    }

We will simply add the @Async to the called method:

However @Async has limitations to keep in mind:

  • it must be applied to public methods only,
  • calling the method decorated with @Async from within the same class won't work,

The method will be something like:

@Asyncpublic void doWorkAsynchronously() {    try {        // the nessesary work        // log the success    }    catch (Exception ex) {        // log the error    }}

And that's it , youve got your asynchronous method readyyyyyy .
image

3. More options:

Other stuff not covered here, that Spring Boot offers:
https://spring.io/guides/gs/async-method/


Original Link: https://dev.to/oum/create-an-asynchronous-method-in-spring-boot-4fkn

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To