springboot集成RestTemplate及常见的用法说明

目录
  • 一、背景介绍 
    • 1、什么是RestTemplate?
    • 2、RestTemplate的优缺点
  • 二、配置RestTemplate
    • 1、引入依赖
    • 2、连接池配置
    • 3、初始化连接池
    • 4、使用示例
  • 三、RestTemplate常用方法
    • 1、getForEntity
    • 2、getForObject
    • 3、postForEntity
    • 4、postForObject
    • 5、postForLocation
    • 6、PUT请求
    • 7、DELETE请求

一、背景介绍 

在微服务都是以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接口主要提供了两种实现方式

1、一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。

2、一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。

其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdk的http请求。

2、RestTemplate的优缺点

  • 优点:连接池、超时时间设置、支持异步、请求和响应的编解码
  • 缺点:依赖别的spring版块、参数传递不灵活

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);
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot 如何使用RestTemplate来调用接口

    目录 使用RestTemplate来调用接口 1.新建一个配置类,配置RestTemplate的Bean import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframe

  • Springboot之restTemplate的配置及使用方式

    目录 基础配置 以下为进阶配置和使用 1 场景 2 依赖 3 配置 4 使用 4.1 GET请求 4.2 POST请求 4.3 上传文件 在springboot项目中,可以直接注入RestTemplate使用,也可进行简单配置 基础配置 @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return

  • springboot restTemplate连接池整合方式

    目录 springboot restTemplate连接池整合 restTemplate 引入apache httpclient RestTemplate配置类 RestTemplate连接池配置参数 测试带连接池的RestTemplate RestTemplate 配置http连接池 springboot restTemplate连接池整合 restTemplate 使用http连接池能够减少连接建立与释放的时间,提升http请求的性能.如果客户端每次请求都要和服务端建立新的连接,即三次握手将

  • 关于SpringBoot大文件RestTemplate下载解决方案

    近期基于项目上使用到的RestTemplate下载文件流,遇到1G以上的大文件,下载需要3-4分钟,因为调用API接口没有做分片与多线程, 文件流全部采用同步方式加载,性能很慢.最近结合网上案例及自己总结,写了一个分片下载tuling/fileServer项目: 1.包含同步下载文件流在浏览器加载输出相关代码: 2.包含分片多线程下载分片文件及合并文件相关代码: 另外在DownloadThread项目中使用代码完成了一个远程RestUrl请求去获取一个远端资源大文件进行多线程分片下载 到本地的一

  • Springboot集成restTemplate过程详解

    一restTemplate简介 restTemplate底层是基于HttpURLConnection实现的restful风格的接口调用,类似于webservice,rpc远程调用,但其工作模式更加轻量级,方便于rest请求之间的调用,完成数据之间的交互,在springCloud之中也有一席之地.大致调用过程如下图 二restTemplate常用方法列表 forObeject跟forEntity有什么区别呢?主要的区别是forEntity的功能更加强大一些,其返回值是一个ResponseEntit

  • springboot集成RestTemplate及常见的用法说明

    目录 一.背景介绍 1.什么是RestTemplate? 2.RestTemplate的优缺点 二.配置RestTemplate 1.引入依赖 2.连接池配置 3.初始化连接池 4.使用示例 三.RestTemplate常用方法 1.getForEntity 2.getForObject 3.postForEntity 4.postForObject 5.postForLocation 6.PUT请求 7.DELETE请求 一.背景介绍 在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用

  • springboot集成activemq的实例代码

    ActiveMQ ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位. 特性 多种语言和协议编写客户端.语言: Java,C,C++,C#,Ruby,Perl,Python,PHP.应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP

  • SpringBoot 集成Kaptcha实现验证码功能实例详解

    在一个web应用中验证码是一个常见的元素.不管是防止机器人还是爬虫都有一定的作用,我们是自己编写生产验证码的工具类,也可以使用一些比较方便的验证码工具.在网上收集一些资料之后,今天给大家介绍一下kaptcha的和springboot一起使用的简单例子. 准备工作: 1.你要有一个springboot的hello world的工程,并能正常运行. 2.导入kaptcha的maven: <!-- https://mvnrepository.com/artifact/com.github.penggl

  • SpringBoot集成RabbitMQ实现用户注册的示例代码

    上一篇已经介绍了什么是rabbitmq以及和springboot集成方法,也介绍了springboot集成邮件的方式,不了解的可以先看以前写的文章. 三者集成 上一篇springboot集成邮件注册的已经介绍了,本篇文章基于这个介绍,我们只需要修改下面几处即可完成3者集成. 实现步骤 添加rabbitmq依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring

  • SpringBoot集成JWT实现token验证的流程

    JWT官网: https://jwt.io/ JWT(Java版)的github地址:https://github.com/jwtk/jjwt 什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).定义了一种简洁的,自包含的方法用于通信双方之间以JSON对象的形式安全的传递信息.因为数字签名的存在,这些信息是可信的,JWT可以使用HMAC算法或者是RSA的公私秘钥对进行签名. JWT请求流程 1. 用户使

  • springboot集成nacos的配置方法

    本文介绍了springboot集成nacos的配置方法,分享给大家,具体如下: nacos仓库:https://github.com/alibaba/nacos nacos介绍文档:https://nacos.io/zh-cn/docs/architecture.html nacos使用例子:https://github.com/nacos-group/nacos-examples springboot配置-集成nacos,例子代码下载 springboot-nacos-consumer spr

  • SpringBoot集成Spring Security的方法

    至今Java能够如此的火爆Spring做出了很大的贡献,它的出现让Java程序的编写更为简单灵活,而Spring如今也形成了自己的生态圈,今天咱们探讨的是Spring旗下的一个款认证工具:SpringSecurity,如今认证框架主流"shiro"和"SpringSecurity",由于和Spring的无缝衔接,使用SpringSecurity的企业也越来越多. 1.Spring Security介绍 Spring security,是一个强大的和高度可定制的身份验

  • springboot集成普罗米修斯(Prometheus)的方法

    Prometheus 是一套开源的系统监控报警框架.它由工作在 SoundCloud 的 员工创建,并在 2015 年正式发布的开源项目.2016 年,Prometheus 正式加入 Cloud Native Computing Foundation,非常的受欢迎. 简介 Prometheus 具有以下特点: 一个多维数据模型,其中包含通过度量标准名称和键/值对标识的时间序列数据 PromQL,一种灵活的查询语言,可利用此维度 不依赖分布式存储: 单服务器节点是自治的 时间序列收集通过HTTP上

  • 浅谈springboot中tk.mapper代码生成器的用法说明

    问:什么是tk.mapper? 答:这是一个通用的mapper框架,相当于把mybatis的常用数据库操作方法封装了一下,它实现了jpa的规范,简单的查询更新和插入操作都可以直接使用其自带的方法,无需写额外的代码. 而且它还有根据实体的不为空的字段插入和更新的方法,这个是非常好用的哈. 而且它的集成非常简单和方便,下面我来演示下使用它怎么自动生成代码. pom中引入依赖,这里引入tk.mybatis.mapper的版本依赖是因为在mapper-spring-boot-starter的新版本中没有

随机推荐