springboot异步任务
在某些不设计数据修改的高并发任务中,有些情况下我们想要达到更好的用户体验感,而不是漫长的等待后台的响应(发邮件)。
- 这个时候可以将这个任务设置为异步任务,即不等待后台相应直接完成后续。
- 异步任务本质上时利用多线程实现的。
异步任务的实现
-
主启动类用注解@EnableAsync开启异步任务支持
@SpringBootApplication @EnableAsync //开启异步注解功能 public class SpringbootTestrApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTestrApplication.class, args); } }
-
建立接口模拟后台长时间响应
@Service public class AsyncService { //告诉spring这是一个异步方法 @Async public void hello(){ try{ Thread.sleep(3000); }catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理。。。"); } }
-
调用接口
@RestController public class AsyncController { @Autowired private AsyncService service; @RequestMapping("/hello") public String hello(){ service.hello(); return "ok"; } }
即使是在线程休眠的情况下,我们的接口还是可以迅速的得到响应。
因为异步任务采用多线程的方式,一个线程继续处理等待,另一个线程立马响应。选择异步任务要注意数据安全问题。