springboot学习入门简易版七---springboot2.0使用@Async异步执行方法(17)

时间:2024-04-19 08:37:25

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

页面显示空,后台日志:

springboot学习入门简易版七---springboot2.0使用@Async异步执行方法(17)

说明异步调用成功,未按顺序执行。

原理:使用aop技术在运行时创建一个单独线程执行

github代码:https://github.com/cslj2013/springboot2.0_log_aop.git