I. How to enable asynchronous in Spring Boot
|
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* The class AsyncConfig.
*/
@Configuration
@EnableAsync
public class AsyncConfig {
}
|
II. How to use the @Async
|
@Service
public class EmailService {
@Async
public void sendEmail (String recipient) {
System.out.println("Sending email to: "+ recipient);
try {
Thread.sleep(5000); // Simulate task takes much time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Finished sending email to: "+ recipient);
}
}
|
|
@RestController
@RequestMapping("/email")
public class EmailController {
private final EmailService emailService;
public EmailController (EmailService emailService) {
this.emailService= emailService;
}
@PostMapping("/send")
public String send (@RequestParam String recipient) {
emailService.sendEmail(recipient);
return"Request processed!";
}
}
|
When the user executes the "/email" API, the response is returned immediately while the email sending continues in the background thread.
III. Asynchronous processing with return values
|
@Async
public CompletableFuture<String>fetchUserData() throws InterruptedException {
Thread.sleep(2000);
return CompletableFuture.completedFuture("User data");
}
|
|
@Async
public CompletableFuture<String>getUserInfo() throws InterruptedException {
Thread.sleep(2000);
return CompletableFuture.completedFuture("User Info");
}
@Async
public CompletableFuture<String>getOrderHistory() throws InterruptedException {
Thread.sleep(3000);
return CompletableFuture.completedFuture("Order History");
}
public StringmergeAsyncTasks() throws Exception {
CompletableFuture<String> userInfo=getUserInfo();
CompletableFuture<String> orderHistory=getOrderHistory();
CompletableFuture.allOf(userInfo, orderHistory).join();
return userInfo.get() +" | "+orderHistory.get();
}
|
IV. Important Note
V. Summary
Whether you need scalable software solutions, expert IT outsourcing, or a long-term development partner, ISB Vietnam is here to deliver. Let’s build something great together—reach out to us today. Or click here to explore more ISB Vietnam's case studies.
[References]









