类说明

AsyncRestTemplate 是 Spring中提供异步的客户端HTTP访问的核心类。与RestTemplate类相似,它提供了一些类似的方法,只不过返回类型不是具体的结果,而是ListenableFuture包装类。
 
通过getRestOperations()方法,对外提供了一个同步的RestTemplate对象,并且通过这个RestTemplate对象来共享错误处理和消息转换。
 
注意:默认情况下,AsyncRestTemplate依靠标准JDK工具来创建HTTP链接。通过使用构造函数来接收AsyncClientHttpRequestFactory接口的具体实现类对象,你可以选用不同的HTTP库,例如Apache HttpComponents,Netty,以及OkHttp。
* Spring's central class for asynchronous client-side HTTP access. Exposes similar methods as RestTemplate, but returns ListenableFuture wrappers as opposed to concrete results.
The AsyncRestTemplate exposes a synchronous RestTemplate via the getRestOperations() method and shares its error handler and message converters with that RestTemplate.
Note: by default AsyncRestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library such as Apache HttpComponents, Netty, and OkHttp by using a constructor accepting an AsyncClientHttpRequestFactory.
 

类图

类图中省略了一些参数类型及重载的方法,在不影响理解的情况下,保证各要素在一幅图中展现。

 

private String result = "";

@Test
public void testAsyncPost() throws Exception {
String posturl = "http://xxxxxx";
String params = "xxxxxx";

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

HttpEntity<Object> hpEntity = new HttpEntity<Object>(params, headers);
AsyncRestTemplate asyncRt = new AsyncRestTemplate();

ListenableFuture<ResponseEntity<String>> future = asyncRt.postForEntity(posturl, hpEntity, String.class);

future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
public void onSuccess(ResponseEntity<String> resp) {
result = resp.getBody();
}
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
});
System.out.println(result);
}

package com.mlxs.common.server.asyncrest;

import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

/**
* Asyncrest: AsyncRestTemplate 异步发生请求测试
*
* @author mlxs
* @since 2016/8/4
*/
@Controller
@RequestMapping("/async")
public class AsyncrestController {
Logger logger = Logger.getLogger(AsyncrestController.class);

@RequestMapping("/fivetime")
@ResponseBody
public String tenTime(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "5秒...";
}

/**
* 同步调用
* @return
*/
@RequestMapping("/sync")
@ResponseBody
public String sync(){
//同步调用
RestTemplate template = new RestTemplate();
String url = "http://localhost:8080/async/fivetime";//休眠5秒的服务
String forObject = template.getForObject(url, String.class);
return "同步调用结束, 结果:" + forObject;
}

/**
* 异步调用
* @return
*/
@RequestMapping("/async")
@ResponseBody
public String async(){
AsyncRestTemplate template = new AsyncRestTemplate();
String url = "http://localhost:8080/async/fivetime";//休眠5秒的服务
//调用完后立即返回(没有阻塞)
ListenableFuture<ResponseEntity<String>> forEntity = template.getForEntity(url, String.class);
//异步调用后的回调函数
forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
//调用失败
@Override
public void onFailure(Throwable ex) {
logger.error("=====rest response faliure======");
}
//调用成功
@Override
public void onSuccess(ResponseEntity<String> result) {
logger.info("--->async rest response success----, result = "+result.getBody());
}
});
return "异步调用结束";
}

}

同步请求:

异步请求:

 

Spring AsyncRestTemplate的更多相关文章

  1. 使用Spring AsyncRestTemplate对象进行异步请求调用

    直接上代码: package com.mlxs.common.server.asyncrest; import org.apache.log4j.Logger; import org.springfr ...

  2. Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header

    { "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...

  3. Spring4.1新特性——Spring MVC增强

    目录 Spring4.1新特性——综述 Spring4.1新特性——Spring核心部分及其他 Spring4.1新特性——Spring缓存框架增强 Spring4.1新特性——异步调用和事件机制的异 ...

  4. 【Spring-web】AsyncRestTemplate源码学习

    2017-01-23 by 安静的下雪天 http://www.cnblogs.com/quiet-snowy-day/p/6343347.html 本篇概要 类说明 类图 简单例子 精辟的内部类 类 ...

  5. Spring MVC 学习总结(九)——Spring MVC实现RESTful与JSON(Spring MVC为前端提供服务)

    很多时候前端都需要调用后台服务实现交互功能,常见的数据交换格式多是JSON或XML,这里主要讲解Spring MVC为前端提供JSON格式的数据并实现与前台交互.RESTful则是一种软件架构风格.设 ...

  6. Spring官方文档翻译

    随笔:有人曾这样评价spring,说它是Java语言的一个巅峰之作,称呼它为Java之美,今天,小编就领大家一起来领略一下spring之美! Spring官方文档:http://docs.spring ...

  7. 撸一撸Spring Cloud Ribbon的原理

    说起负载均衡一般都会想到服务端的负载均衡,常用产品包括LBS硬件或云服务.Nginx等,都是耳熟能详的产品. 而Spring Cloud提供了让服务调用端具备负载均衡能力的Ribbon,通过和Eure ...

  8. 转:Spring历史版本变迁和如今的生态帝国

    Spring历史版本变迁和如今的生态帝国     版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/bntX2jSQfEHy7/article/deta ...

  9. Spring官方文档翻译(1~6章)

    Spring官方文档翻译(1~6章) 转载至 http://blog.csdn.net/tangtong1/article/details/51326887 Spring官方文档.参考中文文档 一.S ...

随机推荐

  1. Elasticsearch 基础入门

    原文地址:Elasticsearch 基础入门 博客地址:http://www.extlight.com 一.什么是 ElasticSearch ElasticSearch是一个基于 Lucene 的 ...

  2. WPF Demo6

    通知项熟悉.数据绑定 using System.ComponentModel; namespace Demo6 { /// <summary> /// 通知项属性 /// </sum ...

  3. Fix Visual Studio 2013 Razor CSHTML Intellisense in Class Library or Console Application

    https://mhusseini.wordpress.com/2015/02/05/fix-visual-studio-2013-razor-cshtml-intellisense-in-class ...

  4. ADO.NET EF 中的实体修改方法

    http://www.cnblogs.com/zfz15011/archive/2010/05/30/1747486.html 1.传统修改模式,看下列代码 using (NorthwindEntit ...

  5. js判断是android访问还是ios访问

    原文地址:http://blog.csdn.net/wy978651775/article/details/9014039 该博主也是转载的,但是没有标明出处. 判断原理: JavaScript是前端 ...

  6. GitLab更新远程分支信息

    项目开发中,当远程分支有变动,有人增加或删除了某些分支,而自己本地没有及时自动刷新出来分支的时候,可以用以下命令来更新以下分支信息 git fetch origin --prune 恩,就酱-

  7. 图片尺寸批量resize的matlab并行代码

    在caffe ImageNet例子中有对图片进行resize的部分,文中使用的是linux shell脚本命令: for name in /path/to/imagenet/val/*.JPEG; d ...

  8. 【BZOJ】4517 [Sdoi2016]排列计数(数学+错排公式)

    题目 传送门:QWQ 分析 $ O(nlogn) $预处理出阶乘和阶乘的逆元,然后求组合数就成了$O(1)$了. 最后再套上错排公式:$ \huge d[i]=(i-1) \times (d[i-1] ...

  9. php变量详细讲解

    变量是用于存储信息的"容器". 定义一个变量的语法: $变量名 = 值; 使用变量的例子: <?php $x=5; $y=6; $z=$x+$y; echo $z; ?> ...

  10. 最强数据集50个最佳机器学习公共数据,可以帮你验证idea!

    1.  寻找数据集の奥义 根据CMU的说法,寻找一个好用的数据集需要注意一下几点: 数据集不混乱,否则要花费大量时间来清理数据. 数据集不应包含太多行或列,否则会难以使用. 数据越干净越好,清理大型数 ...