【微服务~远程调用】RestTemplate基本操作快速入门

举报
陶然同学 发表于 2022/06/23 00:36:38 2022/06/23
【摘要】 🔎这里是【微服务~远程调用】,关注我学习云原生不迷路 👍如果对你有帮助,给博主一个免费的点赞以示鼓励 欢迎各位🔎点赞👍评论收藏⭐️ 👀专栏介绍 【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。 👀本期介绍 本期主要介绍RestTemplate基本操作快速入门 文章目录 RestTemplate ...

🔎这里是【微服务~远程调用】,关注我学习云原生不迷路
👍如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位🔎点赞👍评论收藏⭐️

👀专栏介绍

【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。

👀本期介绍

本期主要介绍RestTemplate基本操作快速入门

文章目录

RestTemplate

概述

搭建环境

基本操作

HttpClient高级

SpringBoot整合HttpClient

概述

配置

测试:get请求

         RestTemplate整合HttpClient

案例:管理员登录

分析

数据库

RestTemplate

概述

  • RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

搭建环境

  • 拷贝BaseResult

  • 编写测试类:TestRest


  
  1. package com.czxy;
  2. public class TestRest {
  3. }

基本操作

GET请求

  • 注意:使用RestTemplate封装数据时,BaseResult必须提供==无参构造==。


  
  1. @Test
  2. public void testFindAll(){
  3. String url = "http://localhost:7778/user";
  4. //1 创建对象
  5. RestTemplate restTemplate = new RestTemplate();
  6. //2 发送请求并获得数据
  7. ResponseEntity<BaseResult> entity = restTemplate.getForEntity(url, BaseResult.class);
  8. //3.1 状态
  9. System.out.println(entity.getStatusCode());
  10. //3.2 响应数据
  11. System.out.println(entity.getBody().getData());
  12. }

GET请求:转换泛型异常

  • 查询用户时,如果返回类型为BaseResult,默认不支持泛型信息。及不支持 BaseResult<List<User>>

    • 需要使用 exchange 设置具体的泛型信息


  
  1. @Test
  2. public void testFindAll2(){
  3. String url = "http://localhost:7778/user";
  4. //1 创建对象
  5. RestTemplate restTemplate = new RestTemplate();
  6. //2 发送请求并获得数据
  7. ResponseEntity<BaseResult<List<User>>> entity = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<BaseResult<List<User>>>() {});
  8. //3 获得响应,并打印
  9. BaseResult<List<User>> baseResult = entity.getBody();
  10. List<User> data = baseResult.getData();
  11. for (User user : data) {
  12. System.out.println(user);
  13. }
  14. }

POST请求


  
  1. @Test
  2. public void testAdd(){
  3. String url = "http://localhost:7778/user";
  4. RestTemplate restTemplate = new RestTemplate();
  5. User user = new User(1,"jack","1234",18);
  6. ResponseEntity<BaseResult> entity = restTemplate.postForEntity(url ,user , BaseResult.class);
  7. System.out.println(entity.getStatusCode());
  8. System.out.println(entity.getBody());
  9. }

PUT请求


  
  1. @Test
  2. public void testUpdate(){
  3. String url = "http://localhost:7778/user";
  4. RestTemplate restTemplate = new RestTemplate();
  5. User user = new User(1,"jack","1234",18);
  6. restTemplate.put(url ,user);
  7. System.out.println("修改成功");
  8. }

Delete请求


  
  1. @Test
  2. public void testDelete(){
  3. String url = "http://localhost:7778/user/1";
  4. RestTemplate restTemplate = new RestTemplate();
  5. restTemplate.delete(url);
  6. System.out.println("删除成功");
  7. }

HttpClient高级

HttpClient 关闭日志输出

  • 基于spring boot 测试启动器,自动开启日志输出

  • spring boot 默认采用logback 进行日志管理的

  • 如何管理日志输出:关闭日志输出

    • 在resources/logback.xml

<configuration debug="false"></configuration>
 

HttpClient连接池

  • 分析

    • 使用HttpClients.custom()可以构建自定义 CloseableHttpClient 对象

      • setConnectionManager 用于配置连接

      • setDefaultRequestConfig 用于配置请求

    • 通过PoolingHttpClientConnectionManager 可以为连接配置连接数和并发数

    • 通过 RequestConfig.custom() 可以配置各种超时时间

  • 代码


  
  1. @Test
  2. public void testDemo01() throws IOException {
  3. //1 配置连接管理
  4. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
  5. // 1.1 设置最大连接数
  6. connectionManager.setMaxTotal(1000);
  7. // 1.2 设置并发访问数
  8. connectionManager.setDefaultMaxPerRoute(20);
  9. //2 请求配置
  10. RequestConfig requestConfig = RequestConfig.custom()
  11. .setConnectTimeout(1000)
  12. .setConnectionRequestTimeout(500)
  13. .setSocketTimeout(10 * 1000)
  14. .build();
  15. // 3 获得工具类
  16. CloseableHttpClient httpClient = HttpClients.custom()
  17. .setConnectionManager(connectionManager)
  18. .setDefaultRequestConfig(requestConfig)
  19. //重定向策略
  20. .setRedirectStrategy(new LaxRedirectStrategy())
  21. .build();
  22. // 4 发送请求
  23. CloseableHttpResponse response = null;
  24. try {
  25. HttpGet httpGet = new HttpGet("http://localhost:7778/user");
  26. response = httpClient.execute(httpGet);
  27. if(response.getStatusLine().getStatusCode() == 200){
  28. String str = EntityUtils.toString(response.getEntity(),"UTF-8");
  29. System.out.println(str);
  30. }
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. } finally {
  34. response.close();
  35. }
  36. }

SpringBoot整合HttpClient

概述

  • SpringBoot官方并没有对HttpClient的启动器。所以我们需要自己完成配置

配置

  • 步骤一:修改yml文件,添加连接池配置


  
  1. # http配置
  2. http:
  3. maxTotal: 300
  4. defaultMaxPerRoute: 50
  5. connectTimeout: 1000
  6. connectionRequestTimeout: 500
  7. socketTimeout: 5000
  • 步骤二: 编写配置类

  
  1. package com.czxy.config;
  2. import lombok.Setter;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.config.RequestConfig;
  5. import org.apache.http.conn.HttpClientConnectionManager;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.impl.client.LaxRedirectStrategy;
  9. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  10. import org.springframework.boot.context.properties.ConfigurationProperties;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. @Configuration
  14. @ConfigurationProperties(prefix = "http")
  15. @Setter
  16. public class HttpConfig {
  17. private Integer maxTotal;
  18. private Integer defaultMaxPerRoute;
  19. private Integer connectTimeout;
  20. private Integer connectionRequestTimeout;
  21. private Integer socketTimeout;
  22. private Integer staleConnectionCheckEnabled;
  23. @Bean
  24. public PoolingHttpClientConnectionManager connectionManager(){
  25. //1 配置连接管理
  26. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
  27. // 1.1 设置最大连接数
  28. connectionManager.setMaxTotal(maxTotal);
  29. // 1.2 设置并发访问数
  30. connectionMan1ager.setDefaultMaxPerRoute(defaultMaxPerRoute);
  31. return connectionManager;
  32. }
  33. @Bean
  34. public RequestConfig requestConfig(){
  35. //2 请求配置
  36. RequestConfig requestConfig = RequestConfig.custom()
  37. .setConnectTimeout(connectTimeout)
  38. .setConnectionRequestTimeout(connectionRequestTimeout)
  39. .setSocketTimeout(socketTimeout)
  40. .build();
  41. return requestConfig;
  42. }
  43. @Bean
  44. public HttpClient httpClient(HttpClientConnectionManager connectionManager, RequestConfig requestConfig){
  45. // 3 获得工具类
  46. CloseableHttpClient httpClient = HttpClients.custom()
  47. .setConnectionManager(connectionManager)
  48. .setDefaultRequestConfig(requestConfig)
  49. //重定向策略
  50. .setRedirectStrategy(new LaxRedirectStrategy())
  51. .build();
  52. return httpClient;
  53. }
  54. }

测试:get请求


  
  1. package com.czxy;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.methods.HttpGet;
  5. import org.apache.http.util.EntityUtils;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import javax.annotation.Resource;
  11. import java.io.IOException;
  12. @RunWith(SpringRunner.class)
  13. @SpringBootTest(classes = HttpApplication.class)
  14. public class TestBootHttp {
  15. @Resource
  16. private HttpClient httpClient;
  17. @Test
  18. public void testDemo01() throws IOException {
  19. String url = "http://localhost:7778/user";
  20. HttpGet httpGet = new HttpGet(url);
  21. HttpResponse response = httpClient.execute(httpGet);
  22. if(response.getStatusLine().getStatusCode() == 200){
  23. String str = EntityUtils.toString(response.getEntity());
  24. System.out.println(str);
  25. }
  26. }
  27. }

RestTemplate整合HttpClient

RestTemplate整合HttpClient -- 配置类


  
  1. package com.czxy.config;
  2. import lombok.Setter;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.config.RequestConfig;
  5. import org.apache.http.conn.HttpClientConnectionManager;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.impl.client.LaxRedirectStrategy;
  9. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  10. import org.springframework.boot.context.properties.ConfigurationProperties;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.http.client.ClientHttpRequestFactory;
  14. import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
  15. import org.springframework.http.converter.HttpMessageConverter;
  16. import org.springframework.http.converter.StringHttpMessageConverter;
  17. import org.springframework.web.client.RestTemplate;
  18. import java.nio.charset.Charset;
  19. import java.util.List;
  20. /**
  21. * @author 桐叔
  22. * @email liangtong@itcast.cn
  23. */
  24. @Configuration
  25. @ConfigurationProperties(prefix = "http")
  26. @Setter
  27. public class HttpConfig {
  28. private Integer maxTotal;
  29. private Integer defaultMaxPerRoute;
  30. private Integer connectTimeout;
  31. private Integer connectionRequestTimeout;
  32. private Integer socketTimeout;
  33. private Integer staleConnectionCheckEnabled;
  34. @Bean
  35. public PoolingHttpClientConnectionManager connectionManager(){
  36. //1 配置连接管理
  37. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
  38. // 1.1 设置最大连接数
  39. connectionManager.setMaxTotal(maxTotal);
  40. // 1.2 设置并发访问数
  41. connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
  42. return connectionManager;
  43. }
  44. @Bean
  45. public RequestConfig requestConfig(){
  46. //2 请求配置
  47. RequestConfig requestConfig = RequestConfig.custom()
  48. .setConnectTimeout(connectTimeout)
  49. .setConnectionRequestTimeout(connectionRequestTimeout)
  50. .setSocketTimeout(socketTimeout)
  51. .build();
  52. return requestConfig;
  53. }
  54. @Bean
  55. public HttpClient httpClient(HttpClientConnectionManager connectionManager, RequestConfig requestConfig){
  56. // 3 获得工具类
  57. CloseableHttpClient httpClient = HttpClients.custom()
  58. .setConnectionManager(connectionManager)
  59. .setDefaultRequestConfig(requestConfig)
  60. //重定向策略
  61. .setRedirectStrategy(new LaxRedirectStrategy())
  62. .build();
  63. return httpClient;
  64. }
  65. @Bean
  66. public ClientHttpRequestFactory requestFactory(HttpClient httpClient ){
  67. return new HttpComponentsClientHttpRequestFactory(httpClient);
  68. }
  69. @Bean
  70. public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
  71. RestTemplate template = new RestTemplate(requestFactory);
  72. //乱码处理
  73. List<HttpMessageConverter<?>> list = template.getMessageConverters();
  74. for (HttpMessageConverter<?> mc : list) {
  75. if (mc instanceof StringHttpMessageConverter) {
  76. ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
  77. }
  78. }
  79. return template;
  80. }
  81. }

测试类


  
  1. package com.czxy;
  2. import com.czxy.domain.User;
  3. import com.czxy.vo.BaseResult;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import org.springframework.web.client.RestTemplate;
  10. import javax.annotation.Resource;
  11. @RunWith(SpringRunner.class)
  12. @SpringBootTest(classes = HttpApplication.class)
  13. public class TestBootRest {
  14. @Resource
  15. private RestTemplate restTemplate;
  16. @Test
  17. public void testAdd(){
  18. String url = "http://localhost:7778/user";
  19. User user = new User(1,"jack","1234",18);
  20. ResponseEntity<BaseResult> entity = restTemplate.postForEntity(url ,user , BaseResult.class);
  21. System.out.println(entity.getStatusCode());
  22. System.out.println(entity.getBody());
  23. }
  24. }

案例:管理员登录

分析

数据库


  
  1. CREATE TABLE t_user(
  2. uid INT PRIMARY KEY AUTO_INCREMENT,
  3. username VARCHAR(50),
  4. `password` VARCHAR(32),
  5. age INT
  6. );
  7. INSERT INTO t_user(uid,username,`password`,age) VALUES(1,'jack','1234',18);

文章来源: blog.csdn.net,作者:陶然同学,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_45481821/article/details/125264143

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。