Spring Boot 线程池完整案例:异步任务并发执行
以下是一个完整的 Spring Boot 线程池案例,演示如何使用 Spring Boot 实现异步任务的并发执行。
步骤 1:添加依赖
首先,您需要在 pom.xml 文件中添加 Spring Boot Web Starter 依赖:
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
步骤 2:创建入口类
创建一个 Spring Boot 应用的入口类,并使用 @EnableAsync 注解启用 Spring 的异步处理功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class ThreadPoolExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ThreadPoolExampleApplication.class, args);
}
}
步骤 3:创建异步任务类
创建一个异步任务类,并在需要执行的任务方法上使用 @Async 注解标记:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
@Async
public void doTask1() throws InterruptedException {
System.out.println('Task1 started.');
Thread.sleep(2000);
System.out.println('Task1 finished.');
}
@Async
public void doTask2() throws InterruptedException {
System.out.println('Task2 started.');
Thread.sleep(2000);
System.out.println('Task2 finished.');
}
@Async
public void doTask3() throws InterruptedException {
System.out.println('Task3 started.');
Thread.sleep(2000);
System.out.println('Task3 finished.');
}
}
步骤 4:创建 RESTful API 控制器
创建一个 RESTful API 控制器,注入异步任务类并创建一个 API 接口,当访问该接口时会触发异步任务执行:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@Autowired
private AsyncTask asyncTask;
@GetMapping('/tasks')
public String doTasks() throws InterruptedException {
asyncTask.doTask1();
asyncTask.doTask2();
asyncTask.doTask3();
return 'Tasks started.';
}
}
运行程序并测试
完成以上代码后,您可以启动 Spring Boot 应用,并访问 http://localhost:8080/tasks 接口,您将会看到三个异步任务被同时执行。
通过使用 @EnableAsync 和 @Async 注解,您可以轻松地使用 Spring Boot 创建线程池并实现异步任务的并发执行。
注意:
- Spring Boot 默认使用
SimpleAsyncTaskExecutor来执行异步任务,它是一个单线程执行器,并不真正使用线程池。如果您需要使用真正的线程池,您可以自定义TaskExecutor并将其配置到 Spring 容器中。 - 在使用异步任务时,需要注意线程安全问题,例如使用共享资源时,需要进行必要的同步操作。
- 建议您根据实际需要配置线程池的大小和参数,以获得最佳性能。
原文地址: http://www.cveoy.top/t/topic/qwSc 著作权归作者所有。请勿转载和采集!