🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
实现异步任务的步骤如下: **1. 创建一个SpringBoot项目** ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> ``` **2. 在启动类上标注注解`@EnableAsync`开启异步支持** ```java @EnableAsync @SpringBootApplication public class Springboot04TaskApplication { public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } } ``` **3. 在需要异步的类或方法上标注注解`@Async`说明当前的类或方法是异步任务** ```java @Slf4j @Service public class AsyncService { @Async public void async01() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("AsyncService -> async01"); } } ``` **4. 其它类的同步方法调用异步方法** ```java @Slf4j @RestController public class AsyncController { @Autowired AsyncService asyncService; @GetMapping("/sync01") public void sync01() { log.info("AsyncController -> sync01 -> 001"); //同步方法中调用异步方法 asyncService.async01(); log.info("AsyncController -> sync01 -> 002"); } } ``` 日志打印顺序如下,根据打印日志的顺序,说明异步任务调用成功了。 ``` 2022-09-07 10:52:31 : AsyncController -> sync01 -> 001 2022-09-07 10:52:31 : AsyncController -> sync01 -> 002 -- 等待5s后打印下面日志 2022-09-07 10:52:36 : AsyncService -> async01 ```