异步调用实现多线程处理任务 | 带你读《SpringBoot实战教程》之十四

简介: 本节重点介绍异步调用

上一篇:定义全局异常处理器 | 带你读《SpringBoot实战教程》之十三
下一篇:官方推荐!SpringBoot这样整合JSP | 带你读《SpringBoot实战教程》之十五

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容

21.异步调用:

在项目中,当访问其它接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行,我们可以使用多线程来并行的处理任务,SpringBoot提供了异步处理方式@Async。
编写AsyncService:

public interface AsyncService {

    Future<String> doTask1()throws Exception;
    Future<String> doTask2()throws Exception;
    Future<String> doTask3()throws Exception;
}

编写AsyncServiceImpl:

@Service
public class AsyncServiceImpl implements AsyncService {
    
    public static Random random =new Random();     

    @Async
    @Override
    public Future<String> doTask1() throws Exception {
            System.out.println("开始做任务一");  
            long start = System.currentTimeMillis();  
            Thread.sleep(random.nextInt(10000));  
            long end = System.currentTimeMillis();  
            System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");  
            return new AsyncResult<>("任务一完成");  
    }

    @Async
    @Override
    public Future<String> doTask2()throws Exception {
        System.out.println("开始做任务二");  
        long start = System.currentTimeMillis();  
        Thread.sleep(random.nextInt(10000));  
        long end = System.currentTimeMillis();  
        System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");  
        return new AsyncResult<>("任务二完成"); 
    }

    @Async
    @Override
    public Future<String> doTask3() throws Exception{
        System.out.println("开始做任务三");  
        long start = System.currentTimeMillis();  
        Thread.sleep(random.nextInt(10000));  
        long end = System.currentTimeMillis();  
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");  
        return new AsyncResult<>("任务三完成"); 
    }

}

在Controller中调用service功能:

@Controller
public class TestController {
    
    @Autowired
    private AsyncService asyncService;    
    
    @RequestMapping("/async")
    @ResponseBody
    public String getEntityById() throws Exception {  
        
        long start = System.currentTimeMillis();  
  
        Future<String> task1 = asyncService.doTask1();  
        Future<String> task2 = asyncService.doTask2();  
        Future<String> task3 = asyncService.doTask3();  
  
        while(true) {  
            if(task1.isDone() && task2.isDone() && task3.isDone()) {  
                // 三个任务都调用完成,退出循环等待  
                break;  
            }  
            Thread.sleep(1000);  
        }  
  
        long end = System.currentTimeMillis();  
  
        return "任务全部完成,总耗时:" + (end - start) + "毫秒";  
    }  

}

要是使用异步的话,还需启动类中开始异步执行。
在启动类上加入@EnableAsync注解。
image.png

执行的结果为:
image.png
image.png

相关文章
|
3月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
659 3
|
1月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
2月前
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
1070 1
|
4月前
|
Java 关系型数据库 MySQL
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
563 2
|
4月前
|
人工智能 安全 Java
Spring Boot 中使用 Function 和异步线程池处理列表拆分任务并汇总结果
在Java开发中,处理大规模数据时常常需要将列表拆分为多个子列表进行异步处理并汇总结果。本文介绍如何在Spring Boot中使用Function和异步线程池实现高效且可维护的代码,涵盖结果封装、线程池配置、列表拆分处理及结果汇总等关键步骤。
209 0
|
5月前
|
SQL JSON Java
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
88 0
|
8月前
|
缓存 NoSQL Java
基于SpringBoot的Redis开发实战教程
Redis在Spring Boot中的应用非常广泛,其高性能和灵活性使其成为构建高效分布式系统的理想选择。通过深入理解本文的内容,您可以更好地利用Redis的特性,为应用程序提供高效的缓存和消息处理能力。
744 79
|
5月前
|
Java Spring
如何优雅的实现 SpringBoot 并行任务
我是小假 期待与你的下一次相遇 ~
139 1
|
5月前
|
前端开发 Java Spring
SpringBoot之异步调用@Ansyc
本文介绍了在Spring Boot中实现异步任务的方法,通过在启动类或线程池配置类上添加`@EnableAsync`注解开启异步功能。详细说明了线程池属性类的定义,包括核心线程数、最大线程数、队列容量等参数配置。同时,文章指出需要在目标方法上使用`@Async`注解以实现异步执行,并列举了`@Async`注解失效的多种情况,如方法被`static`修饰、类未被Spring扫描、方法调用者与被调用方法在同一类中等。此外,还探讨了解决事务与异步之间矛盾的方案,强调了正确使用`@Transactional`注解的重要性。
446 8