springboot系列十二、springboot集成RestTemplate及常见用法
一、背景介绍
在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLConnection
、Apache的Http Client
、Netty的异步HTTP Client, Spring的RestTemplate
。这里介绍的是RestTemplate。RestTemplate底层用还是HttpClient,对其做了封装,使用起来更简单。
1、什么是RestTemplate?
RestTemplate是Spring提供的用于访问Rest服务的客户端,
RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,
可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式
、一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。
、一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。
2、RestTemplate的优缺点:
RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1
@Autowired
RestTemplate simpleRestTemplate;
@Autowired
RestTemplate restTemplate;
二、配置RestTemplate
1、引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、连接池配置
#最大连接数
http.maxTotal: 100
#并发数
http.defaultMaxPerRoute: 20
#创建连接的最长时间
http.connectTimeout: 1000
#从连接池中获取到连接的最长时间
http.connectionRequestTimeout: 500
#数据传输的最长时间
http.socketTimeout: 10000
#提交请求前测试连接是否可用
http.staleConnectionCheckEnabled: true
#可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立
http.validateAfterInactivity: 3000000
3、初始化连接池
package com.example.demo.config; import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; @Configuration
public class RestTemplateConfig {
@Value("${http.maxTotal}")
private Integer maxTotal; @Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute; @Value("${http.connectTimeout}")
private Integer connectTimeout; @Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout; @Value("${http.socketTimeout}")
private Integer socketTimeout; @Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled; @Value("${http.validateAfterInactivity}")
private Integer validateAfterInactivity; @Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
} @Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
} @Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(maxTotal); // 最大连接数
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); //单个路由最大连接数
connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空间时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout) //服务器返回数据(response)的时间,超过抛出read timeout
.setConnectTimeout(connectTimeout) //连接上服务器(握手成功)的时间,超出抛出connect timeout
.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交前检测是否可用
.setConnectionRequestTimeout(connectionRequestTimeout)//从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
} }
4、使用示例
RestTemplate是对HttpCilent的封装,所以,依HttpCilent然可以继续使用HttpCilent。看下两者的区别
HttpCilent:
@RequestMapping("/testHttpClient")
@ResponseBody
public Object getUser(String msg) throws IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://192.168.1.100:8080/User/getAllUser");
CloseableHttpResponse response = closeableHttpClient.execute(get);
return EntityUtils.toString(response.getEntity(), "utf-8");
}
RestTemplate:
@RequestMapping("/testRestTemplate")
@ResponseBody
public Object testRestTemplate() throws IOException {
ResponseEntity result= restTemplate.getForEntity("http://192.168.1.100:8080/User/getAllUser",ResponseEntity.class);
return result.getBody();
}
RestTemplate更简洁了。
三、RestTemplate常用方法
1、getForEntity
getForEntity方法的返回值是一个ResponseEntity<T>
,ResponseEntity<T>
是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。比如下面一个例子:
@RequestMapping("/sayhello")
public String sayHello() {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={1}", String.class, "张三");
return responseEntity.getBody();
}
@RequestMapping("/sayhello2")
public String sayHello2() {
Map<String, String> map = new HashMap<>();
map.put("name", "李四");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);
return responseEntity.getBody();
}
2、getForObject
getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject,举一个简单的例子,如下:
@RequestMapping("/book2")
public Book book2() {
Book book = restTemplate.getForObject("http://HELLO-SERVICE/getbook1", Book.class);
return book;
}
3、postForEntity
@RequestMapping("/book3")
public Book book3() {
Book book = new Book();
book.setName("红楼梦");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
return responseEntity.getBody();
}
- 方法的第一参数表示要调用的服务的地址
- 方法的第二个参数表示上传的参数
- 方法的第三个参数表示返回的消息体的数据类型
4、postForObject
如果你只关注,返回的消息体,可以直接使用postForObject。用法和getForObject一致。
5、postForLocation
postForLocation也是提交新资源,提交成功之后,返回新资源的URI,postForLocation的参数和前面两种的参数基本一致,只不过该方法的返回值为Uri,这个只需要服务提供者返回一个Uri即可,该Uri表示新资源的位置。
6、PUT请求
在RestTemplate中,PUT请求可以通过put方法调用,put方法的参数和前面介绍的postForEntity方法的参数基本一致,只是put方法没有返回值而已。举一个简单的例子,如下:
@RequestMapping("/put")
public void put() {
Book book = new Book();
book.setName("红楼梦");
restTemplate.put("http://HELLO-SERVICE/getbook3/{1}", book, 99);
}
7、DELETE请求
delete请求我们可以通过delete方法调用来实现,如下例子:
@RequestMapping("/delete")
public void delete() {
restTemplate.delete("http://HELLO-SERVICE/getbook4/{1}", 100);
}
springboot系列十二、springboot集成RestTemplate及常见用法的更多相关文章
- SpringBoot系列(十二)过滤器配置详解
SpringBoot(十二)过滤器详解 往期精彩推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件 ...
- SpringBoot系列十二:SpringBoot整合 Shiro
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...
- SpringBoot实战(十二)之集成kisso
关于kisso介绍,大家可以参考官方文档或者是我的博客:https://www.cnblogs.com/youcong/p/9794735.html 一.导入maven依赖 <project x ...
- springboot系列十、springboot整合redis、多redis数据源配置
一.简介 Redis 的数据库的整合在 java 里面提供的官方工具包:jedis,所以即便你现在使用的是 SpringBoot,那么也继续使用此开发包. 二.redidTemplate操作 在 Sp ...
- SpringBoot系列十:SpringBoot整合Redis
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Redis 2.背景 Redis 的数据库的整合在 java 里面提供的官方工具包:jed ...
- springboot系列总结(二)---springboot的常用注解
上一篇文章我们简单讲了一下@SpringBootApplication这个注解,申明让spring boot自动给程序进行必要的配置,他是一个组合注解,包含了@ComponentScan.@Confi ...
- (十二)C语言双指针的常见用法
1.用作函数的返回值,比较常见的是返回分配的堆内存地址. 下面用一个例子进行说明下: /******************************************************** ...
- Springboot系列(七) 集成接口文档swagger,使用,测试
Springboot 配置接口文档swagger 往期推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配 ...
- SpringBoot第十二集:度量指标监控与异步调用(2020最新最易懂)
SpringBoot第十二集:度量指标监控与异步调用(2020最新最易懂) Spring Boot Actuator是spring boot项目一个监控模块,提供了很多原生的端点,包含了对应用系统的自 ...
随机推荐
- 学习2__STM32--汉字显示
汉字显示操作流程 第一,进入主函数 int main(void) { u32 fontcnt; u8 i,j; u8 fontx[];//gbk码 u8 key,t; delay_init(); // ...
- 使用netty编写IM通信界面
前驱知识 WebSocket 维基百科: WebSocket是一种在单个TCP连接上进行全双工通信的协议.WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补 ...
- Fence Repair(poj3253)
题目链接:http://poj.org/problem?id=3253 Description Farmer John wants to repair a small length of the fe ...
- [luogu2657][windy数]
luogu2657 思路 数位dp,记录下上个位置的数,如果当前的数字与上个数字的差值小于2,就不再转移.还是要注意排除前导0.在记忆化的时候,全都是前导0的情况不能记忆化. 代码 #include& ...
- php redis在windows下的部署
1.下载php扩展 下载地址:https://github.com/phpredis/phpredis/downloads 2.将下载php扩展redis放到php的ext目录下,然后在php.ini ...
- R语言 画图roc
这才是我要的滑板鞋~~~~~ #glm模型glm.model=train(y~.,data=data_train, method="glm", metric="ROC&q ...
- k8s 常用命令汇集
通过yaml文件创建: kubectl create -f xxx.yaml (不建议使用,无法更新,必须先delete) kubectl apply -f xxx.yaml (创建+更新,可以重复使 ...
- SQL语句汇总(三)——聚合函数、分组、子查询及组合查询
拖了一个星期,终于开始写第三篇了.走起! 聚合函数: SQL中提供的聚合函数可以用来统计.求和.求最值等等. 分类: –COUNT:统计行数量 –SUM:获取单个列的合计值 –AVG:计算某个列的平均 ...
- Spring + Mybatis 读写分离
项目背景:项目开发中数据库使用了读写分离,所有查询语句走从库,除此之外走主库. 实现思路是: 第一步,实现动态切换数据源:配置两个DataSource,配置两个SqlSessionFactory指向两 ...
- Hbase记录-ZooKeeper API
Zookeeper API ZooKeeper有一个Java和C绑定的官方API.ZooKeeper社区提供了对于大多数语言(.NET,Python等)的非官方API.使用ZooKeeper的API, ...