1. 异步执行
⏰ 关键代码
- ⭕🌏 使用
@EnableAsync
注解开启SpringBoot的异步支持@SpringBootApplication
@EnableAsync
public class DemoAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(DemoAsyncApplication.class, args);
}
}
- ⭕🌏 在需要异步执行的代码上使用
@Async
注解,应用会使用另一个线程执行方法@Async
public Future<String> asyncTask1() throws InterruptedException {
log.info("异步方法 asyncTask1 开始执行,执行线程为{}", Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(10);
log.info("异步方法 asyncTask1 结束执行,执行线程为{}", Thread.currentThread().getName());
return new AsyncResult<>("this is asyncTask1");
}
⏰ Maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.project