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. 原生JS的地区二级联动,很好理解的逻辑

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. CSS text-decoration 属性

    定义和用法 text-decoration 属性规定添加到文本的修饰. 注释:修饰的颜色由 "color" 属性设置. 说明 这个属性允许对文本设置某种效果,如加下划线.如果后代元 ...

  3. 解决PLSQL Developer 插入中文 乱码问题(转)

    原文地址:解决PLSQL Developer 插入中文 乱码问题 PLSQL Developer 插入中文 乱码问题,如图     这个是由于oracle服务器端字符编码 和 Oracle 客户端 字 ...

  4. ActiveMQ producer同步/异步发送消息

    http://activemq.apache.org/async-sends.html producer发送消息有同步和异步两种模式,可以通过代码配置: ((ActiveMQConnection)co ...

  5. paysoft 网关出现EntityRef:expecting;的错误。

    paysoft 网关出现EntityRef:expecting;的错误. 原因是传进去的url里有&字符,之前是自动转义的,现在要手工改成& http://www.runoob.com ...

  6. JAVA工程师面试常见问题集锦

    集锦一: 一.面试题基础总结 1. JVM结构原理.GC工作机制详解 答:具体参照:JVM结构.GC工作机制详解     ,说到GC,记住两点:1.GC是负责回收所有无任何引用对象的内存空间. 注意: ...

  7. 【HTTP】boundary 中一个 = 导致HTTP上传文件失败

    (1)#define ABOUNDARY "----=_Resume_002_0CE7_01D1C649.298A8070" (2)#define ABOUNDARY " ...

  8. laravel composer 安装指定版本以及基本的配置

    1 安装指定的 laravel版本 以下的案例是安装5.2版本 composer create-project laravel/laravel=5.2.* --prefer-dist 2 配置 优化相 ...

  9. win10与centos7的双系统U盘安装(二:安装以及配置centos系统)

    继续第一篇的讲解,接着就是要进入第二部分——安装以及配置centos系统 特别提醒在安装centos之间,注意自己的win10系统进行备份,便于回复安装失败后的系统 1:安装前准备 安装前准备主要是两 ...

  10. springmvc添加定时任务

    springmvc.xml文件中添加如下配置 <bean id="ClearTempRoomLogTask" class="com.test.listener.St ...