spring boot 是由 pivotal 团队提供的全新框架,其设计目的是用来简化新 spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是 spring boot 其实不是什么新的框架,它默认配置了很多框架的使用方式,就像 maven 整合了所有的 jar 包,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);
}
}问题解决,服务端瞬间就会响应给前端数据!
树越是向往高处的光亮,它的根就越要向下,向泥土向黑暗的深处。
以上就是springboot怎么实现异步任务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号