Spring 对异步任务具有很好的支持。这篇文章,我们透过 Spring Boot 来讲解下单发服务模式和请求应答模式。

Spring Boot 集成异步任务

在 Spring Boot 中使用 @EnableAsync 开启异步支持。

  1. @Configuration
  2. @EnableAsync
  3. public class AsyncConfig {
  4. }

现在,我们在 Spring Boot 中,我们只需要通过使用 @Async 注解就能将原来的同步方法变为异步方法。

单发服务模式

多个服务之间逻辑上不存在相互依赖关系,执行先后顺序没有严格的要求,逻辑上可以被并行执行。对于单发服务只有请求,没有应答,很容易设计成异步的。发起服务调用后。立即返回,不需要同步阻塞等待应答。

  1. @Service
  2. public class MsgServer {
  3. @Async
  4. public void sendA() throws Exception {
  5. System.out.println("send A");
  6. Long startTime = System.currentTimeMillis();
  7. Thread.sleep(2000);
  8. Long endTime = System.currentTimeMillis();
  9. System.out.println("耗时:" + (endTime - startTime));
  10. }
  11. @Async
  12. public void sendB() throws Exception {
  13. System.out.println("send B");
  14. Long startTime = System.currentTimeMillis();
  15. Thread.sleep(2000);
  16. Long endTime = System.currentTimeMillis();
  17. System.out.println("耗时:" + (endTime - startTime));
  18. }
  19. }

此时,因为我们添加了 @Async 注解,它就变成了异步方法。

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringApplicationConfiguration(classes = WebMain.class)
  3. public class AsyncTest {
  4. @Autowired
  5. private MsgServer msgServer;
  6. @Test
  7. public void test() throws Exception {
  8. msgServer.sendA();
  9. msgServer.sendB();
  10. }
  11. }

请求应答模式

对于,请求的内容,需要应答,例如我们需要在多个方法调用都完成后,才进行接下来的操作,此时我们可以利用 Java 的 Future-Listener 机制来实现异步服务调用。

  1. @Service
  2. public class MsgFutureServer {
  3. public static Random random = new Random();
  4. @Async
  5. public Future<String> sendA() throws Exception {
  6. System.out.println("send A");
  7. Long startTime = System.currentTimeMillis();
  8. Thread.sleep(2000);
  9. Long endTime = System.currentTimeMillis();
  10. System.out.println("耗时:" + (endTime - startTime));
  11. return new AsyncResult<String>("success");
  12. }
  13. @Async
  14. public Future<String> sendB() throws Exception {
  15. System.out.println("send B");
  16. Long startTime = System.currentTimeMillis();
  17. Thread.sleep(2000);
  18. Long endTime = System.currentTimeMillis();
  19. System.out.println("耗时:" + (endTime - startTime));
  20. return new AsyncResult<String>("success");
  21. }
  22. }

下面的单元测试,在等待完成两个异步任务后,再统计具体耗时时长。

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringApplicationConfiguration(classes = WebMain.class)
  3. public class AsyncFutureTest {
  4. @Autowired
  5. private MsgFutureServer msgFutureServer;
  6. @Test
  7. public void test() throws Exception {
  8. long startTime = System.currentTimeMillis();
  9. Future<String> task1 = msgFutureServer.sendA();
  10. Future<String> task2 = msgFutureServer.sendB();
  11. while(true) {
  12. if(task1.isDone() && task2.isDone() ) {
  13. break;
  14. }
  15. }
  16. long endTime = System.currentTimeMillis();
  17. System.out.println("总耗时:" + (endTime - startTime));
  18. }
  19. }

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务的更多相关文章

  1. Spring Boot 揭秘与实战(七) 实用技术篇 - StateMachine 状态机机制

    文章目录 1. 环境依赖 2. 状态和事件 2.1. 状态枚举 2.2. 事件枚举 3. 状态机配置4. 状态监听器 3.1. 初始化状态机状态 3.2. 初始化状态迁移事件 5. 总结 6. 源代码 ...

  2. Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件

    文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...

  3. Spring Boot 揭秘与实战(七) 实用技术篇 - FreeMarker 模板引擎

    文章目录 1. FreeMaker 代替 JSP 作为页面渲染 2. 生成静态文件 3. 扩展阅读 4. 源代码 Spring Boot 提供了很多模板引擎的支持,例如 FreeMarker.Thym ...

  4. Spring Boot 揭秘与实战 附录 - Spring Boot 公共配置

    Spring Boot 公共配置,配置 application.properties/application.yml 文件中. 摘自:http://docs.spring.io/spring-boot ...

  5. Spring Boot 揭秘与实战 自己实现一个简单的自动配置模块

    文章目录 1. 实战的开端 – Maven搭建 2. 参数的配置 - 属性参数类 3. 真的很简单 - 简单的服务类 4. 自动配置的核心 - 自动配置类 5. spring.factories 不要 ...

  6. Spring Boot 揭秘与实战 源码分析 - 工作原理剖析

    文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...

  7. Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机

    文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...

  8. Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点

    文章目录 1. 继承 AbstractEndpoint 抽象类 2. 创建端点配置类 3. 运行 4. 源代码 Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点. 本 ...

  9. Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控

    文章目录 1. 内置 HealthIndicator 监控检测 2. 自定义 HealthIndicator 监控检测 3. 源代码 Health 信息是从 ApplicationContext 中所 ...

随机推荐

  1. hdu-5889-最短路+网络流/最小割

    Barricade Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total S ...

  2. [CodeForces - 197C] C - Lexicographically Maximum Subsequence

    C - Lexicographically Maximum Subsequence You've got string s, consisting of only lowercase English ...

  3. Hadoop---hu-hadoop1: mv: cannot stat `/home/bigdata/hadoop-2.6.0/logs/hadoop-root-datanode-hu-hadoop1.out.4': No such file or directory

    hu-hadoop1: mv: cannot stat `/home/bigdata/hadoop-2.6.0/logs/hadoop-root-datanode-hu-hadoop1.out.4': ...

  4. sudo执行命令允许教程

    1.说明 在Ubuntu中我们可能经常使用sudo执行一些高权限命令:但在CentOS中默认是不允许普通用户sudo的,如同以下情型 [ls@ls bin]$ sudo ifconfig [sudo] ...

  5. vue 跳外链

    var host = window.location.host;var protocal = window.location.protocolwindow.location.href = protoc ...

  6. Jenkins的安装、启动和配置

    一.Jenkins的安装 1.前提条件:已经成功安装了JDK,因为jenkins是一款基于Java的持续集成工具. 2.准备工具:下载一个jenkins的war包. 3.启动方法:如把jenkins. ...

  7. laravel5.2 开发中打印sql语句

    在 AppServiceProvider 的boot方法中写入 use DB;use Event; if ( env('APP_ENV') == 'dev' ) { DB::connection()- ...

  8. day05列表 类型

    基本使用 1用途:记录多个值,比如人的多个爱好 # ======================================基本使用================================ ...

  9. hdu1693

    题解: 还是插头dp 代码: #include<cstdio> #include<cstring> #include<algorithm> #include< ...

  10. day15-python常用内置模块的使用

    在日常的开发工作中,我们要写很多的python代码,如果都写在一个文件中,会导致代码特别难维护,为了拓展代码的可维护性,我们把函写在不同的文件里,这样每个文件包含的文件就比较少,逻辑更加清楚.在pyt ...