详细讲解springboot如何实现异步任务

网友投稿 295 2022-08-15


详细讲解springboot如何实现异步任务

目录Spring Boot介绍Spring Boot特点异步任务

Spring Boot介绍

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是 Spring Boot 其实不是什么新的框架,它默认配置了很多框架的使用方式,就像 Maven 整合了所有的 Jar 包,Spring Boot 整合了所有的框架。

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) {

xlzjtMql e.printStackTrace();

}

System.out.println("数据正在处理!");

}

}

在SpringBoot启动类上开启异步注解的功能

@SpringBootApplication

//开启了异步注解的功能

@EnableAsync

public class Sprintboot09TestApplication {

public static void main(String[] args) {

SpringApplication.run(Sprintboot09TestApplication.class, args);

}

}

问题解决,服务端瞬间就会响应给前端数据!

树越是向往高处的光亮,它的根就越要向下,向泥土向黑暗的深处。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot整合log4j的踩坑实战记录
下一篇:SpringMVC基于注解方式实现上传下载
相关文章

 发表评论

暂时没有评论,来抢沙发吧~