Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务
Spring 对异步任务具有很好的支持。这篇文章,我们透过 Spring Boot 来讲解下单发服务模式和请求应答模式。
Spring Boot 集成异步任务
在 Spring Boot 中使用 @EnableAsync 开启异步支持。
- @Configuration
- @EnableAsync
- public class AsyncConfig {
- }
现在,我们在 Spring Boot 中,我们只需要通过使用 @Async 注解就能将原来的同步方法变为异步方法。
单发服务模式
多个服务之间逻辑上不存在相互依赖关系,执行先后顺序没有严格的要求,逻辑上可以被并行执行。对于单发服务只有请求,没有应答,很容易设计成异步的。发起服务调用后。立即返回,不需要同步阻塞等待应答。
- @Service
- public class MsgServer {
- @Async
- public void sendA() throws Exception {
- System.out.println("send A");
- Long startTime = System.currentTimeMillis();
- Thread.sleep(2000);
- Long endTime = System.currentTimeMillis();
- System.out.println("耗时:" + (endTime - startTime));
- }
- @Async
- public void sendB() throws Exception {
- System.out.println("send B");
- Long startTime = System.currentTimeMillis();
- Thread.sleep(2000);
- Long endTime = System.currentTimeMillis();
- System.out.println("耗时:" + (endTime - startTime));
- }
- }
此时,因为我们添加了 @Async 注解,它就变成了异步方法。
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringApplicationConfiguration(classes = WebMain.class)
- public class AsyncTest {
- @Autowired
- private MsgServer msgServer;
- @Test
- public void test() throws Exception {
- msgServer.sendA();
- msgServer.sendB();
- }
- }
请求应答模式
对于,请求的内容,需要应答,例如我们需要在多个方法调用都完成后,才进行接下来的操作,此时我们可以利用 Java 的 Future-Listener 机制来实现异步服务调用。
- @Service
- public class MsgFutureServer {
- public static Random random = new Random();
- @Async
- public Future<String> sendA() throws Exception {
- System.out.println("send A");
- Long startTime = System.currentTimeMillis();
- Thread.sleep(2000);
- Long endTime = System.currentTimeMillis();
- System.out.println("耗时:" + (endTime - startTime));
- return new AsyncResult<String>("success");
- }
- @Async
- public Future<String> sendB() throws Exception {
- System.out.println("send B");
- Long startTime = System.currentTimeMillis();
- Thread.sleep(2000);
- Long endTime = System.currentTimeMillis();
- System.out.println("耗时:" + (endTime - startTime));
- return new AsyncResult<String>("success");
- }
- }
下面的单元测试,在等待完成两个异步任务后,再统计具体耗时时长。
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringApplicationConfiguration(classes = WebMain.class)
- public class AsyncFutureTest {
- @Autowired
- private MsgFutureServer msgFutureServer;
- @Test
- public void test() throws Exception {
- long startTime = System.currentTimeMillis();
- Future<String> task1 = msgFutureServer.sendA();
- Future<String> task2 = msgFutureServer.sendB();
- while(true) {
- if(task1.isDone() && task2.isDone() ) {
- break;
- }
- }
- long endTime = System.currentTimeMillis();
- System.out.println("总耗时:" + (endTime - startTime));
- }
- }
源代码
相关示例完整代码: springboot-action
(完)
如果觉得我的文章对你有帮助,请随意打赏。

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务
- 文章链接:http://blog.720ui.com/2017/springboot_07_othercore_async/
Spring Boot 揭秘与实战(七) 实用技术篇 - 异步任务的更多相关文章
- Spring Boot 揭秘与实战(七) 实用技术篇 - StateMachine 状态机机制
文章目录 1. 环境依赖 2. 状态和事件 2.1. 状态枚举 2.2. 事件枚举 3. 状态机配置4. 状态监听器 3.1. 初始化状态机状态 3.2. 初始化状态迁移事件 5. 总结 6. 源代码 ...
- Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件
文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...
- Spring Boot 揭秘与实战(七) 实用技术篇 - FreeMarker 模板引擎
文章目录 1. FreeMaker 代替 JSP 作为页面渲染 2. 生成静态文件 3. 扩展阅读 4. 源代码 Spring Boot 提供了很多模板引擎的支持,例如 FreeMarker.Thym ...
- Spring Boot 揭秘与实战 附录 - Spring Boot 公共配置
Spring Boot 公共配置,配置 application.properties/application.yml 文件中. 摘自:http://docs.spring.io/spring-boot ...
- Spring Boot 揭秘与实战 自己实现一个简单的自动配置模块
文章目录 1. 实战的开端 – Maven搭建 2. 参数的配置 - 属性参数类 3. 真的很简单 - 简单的服务类 4. 自动配置的核心 - 自动配置类 5. spring.factories 不要 ...
- Spring Boot 揭秘与实战 源码分析 - 工作原理剖析
文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...
- Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机
文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...
- Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点
文章目录 1. 继承 AbstractEndpoint 抽象类 2. 创建端点配置类 3. 运行 4. 源代码 Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点. 本 ...
- Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控
文章目录 1. 内置 HealthIndicator 监控检测 2. 自定义 HealthIndicator 监控检测 3. 源代码 Health 信息是从 ApplicationContext 中所 ...
随机推荐
- hdu-5889-最短路+网络流/最小割
Barricade Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total S ...
- [CodeForces - 197C] C - Lexicographically Maximum Subsequence
C - Lexicographically Maximum Subsequence You've got string s, consisting of only lowercase English ...
- 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': ...
- sudo执行命令允许教程
1.说明 在Ubuntu中我们可能经常使用sudo执行一些高权限命令:但在CentOS中默认是不允许普通用户sudo的,如同以下情型 [ls@ls bin]$ sudo ifconfig [sudo] ...
- vue 跳外链
var host = window.location.host;var protocal = window.location.protocolwindow.location.href = protoc ...
- Jenkins的安装、启动和配置
一.Jenkins的安装 1.前提条件:已经成功安装了JDK,因为jenkins是一款基于Java的持续集成工具. 2.准备工具:下载一个jenkins的war包. 3.启动方法:如把jenkins. ...
- laravel5.2 开发中打印sql语句
在 AppServiceProvider 的boot方法中写入 use DB;use Event; if ( env('APP_ENV') == 'dev' ) { DB::connection()- ...
- day05列表 类型
基本使用 1用途:记录多个值,比如人的多个爱好 # ======================================基本使用================================ ...
- hdu1693
题解: 还是插头dp 代码: #include<cstdio> #include<cstring> #include<algorithm> #include< ...
- day15-python常用内置模块的使用
在日常的开发工作中,我们要写很多的python代码,如果都写在一个文件中,会导致代码特别难维护,为了拓展代码的可维护性,我们把函写在不同的文件里,这样每个文件包含的文件就比较少,逻辑更加清楚.在pyt ...