什么是异步调用?
异步调用无需等待上一步程序执行完成即可执行。在开发项目中可以使用多线程来并行处理或者使用SpringBoot提供的@Async处理。
1、启动类上需要添加@EnableAsync
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、声明异步方法
public interface AsyncService {
/**
* 测试异步执行方法1
*/
void progressOne();
/**
* 测试异步方法2
*/
void progressTwo();
}
3、异步类上加上@Component,异步方法上加上@Async
@Component
public class AsyncServiceImpl implements AsyncService {
private static final Logger logger = LoggerFactory.getLogger(
AsyncServiceImpl.class);
@Override
@Async
public void progressOne() {
long start = System.currentTimeMillis();
logger.info("=========第一个程序开始执行,开始时间:{}==========", start);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
logger.info("=========第一个程序结束时间:{}==========", end);
logger.info("=========第一个程序开始结束花费时间:{}==========", (end - start));
}
@Override
@Async
public void progressTwo() {
long start = System.currentTimeMillis();
logger.info("=========第二个程序开始执行时间:{}==========", start);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
logger.info("=========第二个程序结束时间:{}==========", end);
logger.info("=========第二个程序开始结束花费时间:{}==========", (end - start));
}
}
3、控制类调用异步方法
@RestController
@RequestMapping("demo")
public class AsyncController {
private static final Logger logger = LoggerFactory.getLogger(AsyncController.class);
@Resource
AsyncService asyncService;
@GetMapping("/async")
public String AsyncDemo() {
long start = System.currentTimeMillis();
asyncService.progressOne();
asyncService.progressTwo();
long end = System.currentTimeMillis();
logger.info("进程总时间:", (end - start));
return "OK";
}
}
4、启动服务,测试执行结果
执行结果可见,方法1、方法2同时执行(开始时间相同)。即异步执行生效。