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.
Let’s 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
@EnableAsync
public 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:
@Async
public void doWorkAsynchronously() {
try {
// the nessesary work
// log the success
}
catch (Exception ex) {
// log the error
}
}
And that's it 😎, you’ve got your asynchronous method readyyyyyy 😉.
3. More options:
Other stuff not covered here, that Spring Boot offers:
https://spring.io/guides/gs/async-method/
Top comments (1)
Now the challenge is making it return a result via long polling, websocket, messaging, etc. This is the hard part. Doing it in a way that will scale across the cluster is the tricky part.