springboot学习入门简易版七---springboot2.0使用@Async异步执行方法(17)
Posted cslj2013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot学习入门简易版七---springboot2.0使用@Async异步执行方法(17)相关的知识,希望对你有一定的参考价值。
1启动类开启异步调用注解
@SpringBootApplication @EnableAsync //开启异步调用 public class StartApplication {
不开启则异步调用无效
2编写异步调用方法
@RestController public class AsyncController { private final static Logger logger=LoggerFactory.getLogger(WebLogAspect.class); @Autowired private AsyncService asyncService; @RequestMapping("/testAsync") public String testAsync() { logger.info("1"); String result=asyncService.asynTest(); logger.info("4"); return result; } }
@Service public class AsyncService { private final static Logger logger=LoggerFactory.getLogger(WebLogAspect.class); @Async //相当于重新开辟单独线程执行该方法 public String asynTest() { logger.info("2"); try { Thread.sleep(5000); }catch(Exception e) { } logger.info("3"); return "success"; } }
3 访问:http://localhost:8080/testAsync
页面显示空,后台日志:
说明异步调用成功,未按顺序执行。
原理:使用aop技术在运行时创建一个单独线程执行
github代码:https://github.com/cslj2013/springboot2.0_log_aop.git
以上是关于springboot学习入门简易版七---springboot2.0使用@Async异步执行方法(17)的主要内容,如果未能解决你的问题,请参考以下文章
springboot学习入门简易版一---springboot2.0介绍
springboot学习入门简易版五---springboot2.0整合jsp(11)
springboot学习入门简易版四---springboot2.0静态资源访问及整合freemarker视图层
springboot学习入门简易版八---springboot2.0多环境配置整合mybatis mysql8+(19-20)