登录
首页 >  文章 >  java教程

springboot怎么实现异步任务

来源:亿速云

时间:2024-04-25 08:12:37 284浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是文章学习者,那么本文《springboot怎么实现异步任务》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

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);
    }

}

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

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>