@EnablrAsync
时间: 2024-04-02 22:29:33 浏览: 16
@EnableAsync是Spring Boot中的一个注解,用于开启异步方法的支持。它可以应用在启动类上或者方法上,以实现异步调用的功能[^1]。
使用示例:
1. 在启动类上加上注解:@EnableAsync
```java
@EnableAsync
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. 在方法上加上注解:@Async
```java
@Service
public class MyService {
@Async
public void asyncMethod() {
// 异步执行的方法体
}
}
```
3. 编写配置类,定义线程池
```java
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(10);
executor.setThreadNamePrefix("MyAsyncThread-");
executor.initialize();
return executor;
}
}
```
通过以上配置,我们可以在controller层或者service层的方法中使用@Async注解来实现异步调用。当调用被标记为@Async的方法时,Spring会将其放入线程池中执行,而不会阻塞主线程的执行。这样可以提高系统的并发能力和响应速度。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)