本篇文章小编给大家分享一下springboot实现异步任务代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
Spring Boot特点
1)创建独立的Spring应用程序;
2)直接嵌入Tomcat,Jetty或Undertow,无需部署WAR文件;
3)提供推荐的基础POM文件(starter)来简化Apache Maven配置;
4)尽可能的根据项目依赖来自动配置Spring框架;
5)提供可以直接在生产环境中使用的功能,如性能指标,应用信息和应用健康检查;
6)开箱即用,没有代码生成,不需要配置过多的xml。同时也可以修改默认值来满足特定的需求。
7)其他大量的项目都是基于Spring Boot之上的,如Spring Cloud。
异步任务
实例:
在service中写一个hello方法,让它延迟三秒
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理!");
}
}
让Controller去调用这个业务
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "ok";
}
}
启动SpringBoot项目,我们会发现三秒后才会响应ok。
所以我们要用异步任务去解决这个问题,很简单就是加一个注解。
在hello方法上@Async注解
@Service
public class AsyncService {
//异步任务
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理!");
}
}
在SpringBoot启动类上开启异步注解的功能
@SpringBootApplication
//开启了异步注解的功能
@EnableAsync
public class Sprintboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Sprintboot09TestApplication.class, args);
}
}
问题解决,服务端瞬间就会响应给前端数据!