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

2022年4月23日07:58:43

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) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理!");
    }
}

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

@SpringBootApplication
//开启了异步注解的功能
@EnableAsync
public class Sprintboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Sprintboot09TestApplication.class, args);
    }

}

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

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

  • 作者:汪汪程序员  
  • 原文链接:https://www.cnblogs.com/H-scholar/p/16114146.html
    更新时间:2022年4月23日07:58:43 ,共 1341 字。