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项目一个监控模块,提供了很多原生的端点,包含了对应用系统的自 ...
随机推荐
- [hdu3466]Proud Merchants
题目描述 Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and po ...
- shell(1)-磁盘shell
查看硬盘的大小脚本[root@localhost ~]# vi repboot.sh#!/bin/bash# To show usage of /boot directory and mode of ...
- react组件在项目中的应用(基础知识)
上图我是定义了5个模块,全部都渲染在一个组件里面.可以先看看我的代码结构 我将Hello文件夹下的index.jsx文件作为父组件,最后渲染在根组件中. 那我们怎么输出这个Hello组件呢?要达到上图 ...
- css实现单选效果,看看有趣的tabIndex
以前我实现单选变色几乎都是用js实现的,今天看到有个css属性可以直接实现单选变色,很开心啊~ 话不多说看效果 实现的代码如下 下面我们看看用focus实现别的有趣的效果 话不多说看效果 实现的代码如 ...
- Sublime Text3—Code Snippets(自定义代码片段)
摘要 程序员总是会不断的重复写一些简单的代码片段,为了提高编码效率,我们可以把经常用到的代码保存起来再调用. 平时用sublime安装各种插件,使用Tab键快速补全,便是snippets(可译为代码片 ...
- python3之rabbitMQ
1.RabbitMQ介绍 RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现.AMQP 的出现其实也是应了广大人民群众的需求,虽然在同步消息 ...
- Python Numpy shape 基础用法(转自他人的博客,如涉及到侵权,请联系我)
Python Numpy shape 基础用法 shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度.它的输入 ...
- diff目录或文件比较
转载 2014年12月16日 19:16:54 1937 [功能] 以行的方式比较文本文件的异同处 若要比较目录,则会比较相同文件名的文件[参数] -b 忽略空格数目 ...
- (转)Node.js module.exports与exports
本文转自Node.js module.exports与exports 作者: chemdemo 折腾Node.js有些日子了,下面将陆陆续续记录下使用Node.js的一些细节. 熟悉Node.js的童 ...
- 5个强大的Java分布式缓存框架
在开发中大型Java软件项目时,很多Java架构师都会遇到数据库读写瓶颈,如果你在系统架构时并没有将缓存策略考虑进去,或者并没有选择更优的缓存策略,那么到时候重构起来将会是一个噩梦.本文主要是分享了5 ...