
原文网址Spring注解--Async异步执行的方法-CSDN博客简介本文介绍Spring的Async的用法。Async是用来异步执行任务的。基础代码正常情况下执行两个任务是这样的Controllerpackage com.knife.example.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; Slf4j Api(tags 测试) RequestMapping(test) RestController public class HelloController { Autowired private HelloService helloService; ApiOperation(测试1) PostMapping(test1) public void test() { helloService.task1(); helloService.task2(); } }Servicepackage com.knife.example.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; Slf4j Component public class HelloService { public void task1() { log.info(开始任务1); long start System.currentTimeMillis(); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } long end System.currentTimeMillis(); log.info(完成任务1耗时 (end - start) 毫秒); } public void task2() { log.info(开始任务2); long start System.currentTimeMillis(); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } long end System.currentTimeMillis(); log.info(完成任务2耗时 (end - start) 毫秒); } }它的结果是是顺序执行的。2024-07-07 15:53:00.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 开始任务1 2024-07-07 15:53:03.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 完成任务1耗时3000毫秒 2024-07-07 15:53:03.067 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 开始任务2 2024-07-07 15:53:06.073 INFO 1044 --- [nio-8080-exec-1] c.knife.example.controller.HelloService : 完成任务2耗时3006毫秒使用异步加快速度假如上边task1和task2是不相关的那完全可以同时运行加快速度下边就用异步来做1.启用异步EnableAsync在启动类上加EnableAsyncpackage com.knife.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; EnableAsync SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }2.将方法标记为Async为便于维护全文已转移到此网址Spring-Async异步执行的方法 - 自学精灵