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. /etc/fstab 解析

    http://www.codesec.net/view/39930.html root@qs-wg-db1 /]# cat /etc/fstab LABEL=/ / ext3 defaults 1 1 ...

  2. gcc连接脚本lds详解

    转载:blog.chinaunix.net/uid-28685940-id-3889918.html 我们对每个c或者汇编文件进行单独编译,但是不去连接,生成很多.o 的文件,这些.o文件首先是分散的 ...

  3. Ps6 已具备图层搜索功能

    层多了,找一个层非常考验我们的眼里,不过Photoshop cs6带来了福音,终于有搜索了:

  4. php 方法笔记 比file_get_contents好

    /*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s.*/ private function curl_get_contents($url,$timeou ...

  5. sonar使用故障Unable to load component class org.sonar.scanner.report.ActiveRulesPublisher/Unable to load component interface org.sonar.api.batch.rule.ActiveRules: NullPointerException

    nginx后两个sonar负载分担 解决办法 Credit to @teryk-sonarsource-team, just making it an answer: Delete the direc ...

  6. 11.线程通信CountDownLatch

    package demo2; import java.util.concurrent.CountDownLatch; /** * Created by liudan on 2017/7/27. */ ...

  7. C#创建word,操作、读写

    要使用C#操作word,首先要添加引用: 1.添加引用->COM->Microsoft Word 11.0 Object Library 2.在.cs文件中添加 using Word;下面 ...

  8. 安装Office2007时出现1706错误的解决方案

    前几天,重做了系统.周末因为接到一笔单子,很兴奋啊.第一次接到私活.然后就装Office2007,打算看需求的.居然安装的时候出现错误,提示1706错误,后面一串错误信息,也懒得看,以为是文件坏了. ...

  9. Android -- Broadcast接收

    Broadcast是Android四大组件之一,是一种广泛运用的在应用程序之间传输信息的机制.最经典的举例是: “我们拿广播电台来做个比方.我们平常使用收音机收音是这样的:许许多多不同的广播电台通过特 ...

  10. FormBorderStyle为None的时候如何拖动窗体

    //为DllImport导出命名空间, using System.Runtime.InteropServices; public partial class Form1 : System.Window ...