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项目一个监控模块,提供了很多原生的端点,包含了对应用系统的自 ...
随机推荐
- luogu2024 食物链 (并查集)
把一个点拆成三个,分别对应它的同类.它的猎物和它的天敌,这样的话(以下的相等都是并查集意义上的): 如果令a,b同类,那么a的猎物不能是b的同类,a的天敌不能是b的同类 如果令a吃b,那么a的同类不能 ...
- 深入理解Adaboost算法
理解算法确实是欲速则不达,唯有一步一步慢慢看懂,然后突然觉得写的真的太好了,那才是真的有所理解了. Adaboost的两点关键点: 1. 如何根据弱模型的表现更新训练集的权重: 2. 如何根据弱模型的 ...
- SDL_BlitSurface
SDL_BlitSurface Use this function to perform a fast surface copy to a destination surface. Contents ...
- Luogu 1351 NOIP 2014 联合权值(贪心,计数原理)
Luogu 1351 NOIP 2014 联合权值(贪心,计数原理) Description 无向连通图 G 有 n 个点,n-1 条边.点从 1 到 n 依次编号,编号为 i 的点的权值为 Wi, ...
- [luogu2822][组合数问题]
题目链接 题解: 对于上面和下面的式子进行分解质因数,然后看看上面的质因数个数减去下面的质因数个数能不能达到k的质因数的要求即可. 分解质因数的时候用对于阶乘分解质因数的常用方法:比如要求1999!中 ...
- 去除外显子低质量reads时弹出错误“Invalid quality score value (char '#' ord 35 quality value -29) on line 4”和“Invalid quality score value (char '.' ord 46 quality value -18) on line 12”的解决方法
楼主跑以下程序时分别弹出了“fastq_quality_filter: Invalid quality score value (char '.' ord 46 quality value -18) ...
- idea 显示properties 中文
有时我们打开.properties文件时,中文显示为utf8编码格式,可以在file->setting->editor->file encodings下 把transparent n ...
- Int2BinaryString.java
/****************************************************************************** * Compilation: javac ...
- 超详细从零记录Hadoop2.7.3完全分布式集群部署过程
超详细从零记录Ubuntu16.04.1 3台服务器上Hadoop2.7.3完全分布式集群部署过程.包含,Ubuntu服务器创建.远程工具连接配置.Ubuntu服务器配置.Hadoop文件配置.Had ...
- context configure and clock schedule
每个窗口都有自己的context,这里演示怎么配置context以及如何实现定时器...... #-*- coding:gbk -*- import pyglet platform=pyglet.wi ...