异步任务
【为什么要异步任务】
- 前端需要加载一个页面,里面存在很多数据,需要从后端调取,调取数据很慢
- 前端先加载一个其他的页面,后端再调取数据,两者异步
- 当两者都加载完后,界面就显示出来了
举例
- 调取index.html但是存在数据很多,加载需要等待时间
- 在login.html后,调取数据,先去调取一个正在加载的界面
- 然后等待调取数据成功后,再次调用index.html
SpringBoot异步任务
步骤
编写一个Service【关于线程的】AsyncService
@Service
public class AsyncService {
@Async
public void hello(){
System.out.println("数据正在读取");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("数据读取完成");
}
}
写一个Controller
@Controller
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
@ResponseBody
public String hello() {
asyncService.hello();
return "okkkk";
}
}
开启异步注解功能
@EnableAsync
结果
先显示读取数据,同时转圈圈,3秒后显示出页面,然后控制台输出数据读取完成