2024.6.3 Monday
Contents
- 17. Asynchronous, Timed, and Email Tasks
- 17.1. Asynchronous Tasks
17. Asynchronous, Timed, and Email Tasks
In our work, we often need to handle asynchronous tasks. For example, when sending an email on a website, the backend sends the email while the frontend might become unresponsive until the email is sent, causing a delay in the response. To manage these tasks, we generally use multithreading. There are also timed tasks, such as analyzing the previous day’s log information at midnight. Additionally, there’s email sending—did you know that the predecessor of WeChat was also an email service? How are these things implemented? Actually, SpringBoot provides us with the corresponding support. It’s very easy to get started; we just need to enable some annotation support and configure some configuration files! Let’s take a look~
17.1. Asynchronous Tasks
17.1.1. Create a new springboot-09-test project
When creating a project, if you encounter “Initialization failed for ‘https://start.spring.io/’ Please check URL, network, and proxy settings,” the solution is: 【Spring Common Errors】Initialization failed for ‘https://start.spring.io‘-Aliyun Developer Community (aliyun.com)
Add Maven support (click the plus sign in Project Structure->Modules to add the corresponding project), conventionally modify the Maven, JDK, and Java version in settings, and the JDK and Java version in Project Structure. Update the Spring Framework version in pom to 2.7.13, add Thymeleaf dependency in pom.xml, and reload Maven.
Remove unnecessary files.
17.1.2. Create a service package
17.1.2.1. Create a class AsyncService
Asynchronous processing is very common. For instance, when sending an email on a website, the backend handles the email sending, causing the frontend to be unresponsive until the email is sent. Therefore, we usually use multithreading to handle these tasks. Write a method that pretends to process data, use a thread to set some delay, simulating a synchronous wait situation:
package com.P51.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Processing data");
}
}
17.1.3. Create a controller package
17.1.3.1. Create an AsyncController class
package com.P51.controller;
import com.P51.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello(); // Wait for three seconds
return "finished";
}
}
17.1.4. Run Springboot09TestApplication.java
【Synchronous Wait】 Run http://localhost:8080/hello and wait for three seconds before “finished” is displayed on the webpage, while “Processing data” is printed in the console.
Problem: If we want users to get a message immediately, we can handle it in the background using multithreading. However, manually implementing multithreading each time is too cumbersome. We can simply use an easy method: add a simple annotation to our method.
17.1.5. Modify Springboot09TestApplication.java
package com.P51;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
// Enable asynchronous annotation functionality
@EnableAsync
@SpringBootApplication
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
17.1.6. Modify AsyncService.java
package com.P51.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
// Tell Spring this is an asynchronous method
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Processing data");
}
}
17.1.7. Restart Springboot09TestApplication.java
【Asynchronous Task】 Run http://localhost:8080/hello to immediately display “finished” on the webpage. After three seconds, “Processing data” is printed in the console.