Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务
拓展阅读: http://www.jianshu.com/p/86e915d616c4

发表于 2017-01-06 | Spring框架 | SpringBoot

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

springboot 异步任务的更多相关文章

  1. 新手也能看懂的 SpringBoot 异步编程指南

    本文已经收录自 springboot-guide : https://github.com/Snailclimb/springboot-guide (Spring Boot 核心知识点整理. 基于 S ...

  2. springboot异步线程(二)

    前言 本篇文章针对上篇文章springboot异步线程,有一位大佬在评论中提出第一点是错误的,当时看到了这个问题,最近刚好有空,针对第一点的问题去搜索了不少的文章: 问题 我在文章中第一点去验证:Sc ...

  3. springboot异步线程

    前言 最近项目中出现了一个问题,发现自己的定时器任务在线上没有执行,但是在线下测试时却能执行,最后谷歌到了这篇文章SpringBoot踩坑日记-定时任务不定时了?; 本篇文章主要以自己在项目中遇到的问 ...

  4. SpringBoot异步编程

    异步调用:当我们执行一个方法时,假如这个方法中有多个耗时的任务需要同时去做,而且又不着急等待这个结果时可以让客户端立即返回然后,后台慢慢去计算任务.当然你也可以选择等这些任务都执行完了,再返回给客户端 ...

  5. SpringBoot学习笔记(七):SpringBoot使用AOP统一处理请求日志、SpringBoot定时任务@Scheduled、SpringBoot异步调用Async、自定义参数

    SpringBoot使用AOP统一处理请求日志 这里就提到了我们Spring当中的AOP,也就是面向切面编程,今天我们使用AOP去对我们的所有请求进行一个统一处理.首先在pom.xml中引入我们需要的 ...

  6. SpringBoot 异步 定时任务 邮件

    springboot异步 一: 在 MyConfiguration.java 中开启注解 @Configuration//指明当前类是一个配置类:就是来替代之前的Spring配置文件@EnableAs ...

  7. 带着新人学springboot的应用09(springboot+异步任务)

    本来想说说检索的,不过不知道什么鬼,下载ElasticSearch太慢了,还是放一下,后面有机会再补上!今天就说个简单的东西,来说说任务. 什么叫做任务呢?其实就是类中实现了一个什么功能的方法.常见的 ...

  8. springboot 异步调用Async使用方法

    引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在spring 3. ...

  9. SpringBoot 异步输出 Logback 日志

    一.介绍 1.1 Logback Logback是由log4j创始人设计的另一个开源日志组件,它分为下面下个模块: logback-core:其它两个模块的基础模块 logback-classic:它 ...

随机推荐

  1. SpringMVC 学习笔记(二) @RequestMapping、@PathVariable等注解

    版权声明:本文为博主原创文章,博客地址:http://blog.csdn.net/a67474506?viewmode=contents 1.1. @RequestMapping映射请求 Spring ...

  2. [转].net reactor 学习系列(二)---.net reactor界面各功能说明

    安装了.net reactor之后,可以在安装目录下找到帮助文档REACTOR_HELP.chm,目前没有中文版本,里面详细介绍了.net reactor的各功能及使用场景.本系列文章是基于此帮助文档 ...

  3. POJ 1293 - Duty Free Shop 01背包记录所选物品

    裸的01背包.dp[x]只要是bool型记录当前空间是否可用.. 而为了找到用了哪些物品..dp[x]设置为int型..进行记录.. Program: #include<iostream> ...

  4. Windows Embedded Compact 7网络编程概述(下)

    11.1.1 Select I/O模型 在Windows CE中,Select模型是唯一被支持的I/O模型.Select I/O模型就是利用select函数对I/O进行管理. 函数select的功能在 ...

  5. LeetCode89:Gray Code

    The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...

  6. springmvc整合slf4j、log4j记录文本日志

    一.配置pom.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 3 ...

  7. C#类和结构体的异同点简单总结

    类和结构的异同点?异:  1.关键字不同 一个是class,一个是struct  2.类型不同,一个是引用类型,一个是值类型(一个堆区,一个栈区)        3.成员不同,结构体没有默认的构造函数 ...

  8. [Android Studio] Android Studio如何提示函数用法

    Eclipse有一个很好的功能,就是当你代码调用某个android API时,鼠标移到对应的函数或者方法上,就会自动有一个悬 浮窗提示该函数的说明(所包含的参数含义,该方法功能).迁移到Android ...

  9. Redis主从集群以及Sentinel的配置

    安装完redis后,修改几个redis从节点的配置文件redis.conf,主要是加入主节点位置 slaveof 另外需要修改的地方包括,这样允许其他的从节点连入 bind 0.0.0.0 prote ...

  10. go语言基础之普通参数列表

    1.普通参数列表 (备注:只有一个参数) 示例1: package main //必须有一个main包 import "fmt" //有参无返回值函数的定义,普通参数列表 //定义 ...