springboot整合异步操作
时间: 2023-10-23 09:11:43 浏览: 87
Spring Boot提供了基于注解的异步处理,可以使用@EnableAsync注解开启异步处理。在项目的启动类上添加@EnableAsync注解即可。同时,也可以在service方法上添加@Async注解实现异步处理批量操作。下面是示例代码:
1.在应用application中添加@EnableAsync注解:
```
@EnableAsync //开启基于注解版的异步处理
@SpringBootApplication
public class Springboot11TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot11TaskApplication.class, args);
}
}
```
2.在项目的启动类上添加@EnableAsync注解:
```
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SpringbootexampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootexampleApplication.class, args);
}
}
```
3.在service方法上添加@Async注解:
```
@Service
public class AsyncService {
@Async
public void batchAdd(){
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("批量新增数据完成");
}
}
```
阅读全文