springboot 配置线程池 @Async使用该线程池
时间: 2023-11-29 10:45:05 浏览: 132
以下是Springboot配置线程池并使用@Async注解的方法:
1.在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
```
2.创建一个ThreadPoolConfig类,用于配置线程池:
```java
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
```
3.在需要异步执行的方法上添加@Async注解,并指定线程池名称:
```java
@Service
public class MyService {
@Async("myExecutor")
public void asyncMethod() {
// 异步执行的方法体
}
}
```
4.在Controller中调用异步方法:
```java
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public String async() {
myService.asyncMethod();
return "异步方法已经执行";
}
}
```
5.启动应用程序并访问“/async”URL,异步方法将在后台线程池中执行。
阅读全文