这里是【微服务~远程调用】,关注我学习云原生不迷路
如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位点赞评论收藏⭐️
【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。
本期主要介绍RestTemplate基本操作快速入门
RestTemplate
概述
搭建环境
基本操作
HttpClient高级
SpringBoot整合HttpClient
概述
配置
测试:get请求
RestTemplate整合HttpClient
案例:管理员登录
分析
数据库
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
拷贝BaseResult
编写测试类:TestRest
package com.czxy;
public class TestRest {
}
注意:使用RestTemplate封装数据时,BaseResult必须提供==无参构造==。
@Test
public void testFindAll(){
String url = "http://localhost:7778/user";
//1 创建对象
RestTemplate restTemplate = new RestTemplate();
//2 发送请求并获得数据
ResponseEntity entity = restTemplate.getForEntity(url, BaseResult.class);
//3.1 状态
System.out.println(entity.getStatusCode());
//3.2 响应数据
System.out.println(entity.getBody().getData());
}
查询用户时,如果返回类型为BaseResult,默认不支持泛型信息。及不支持 BaseResult>
需要使用 exchange 设置具体的泛型信息
@Test
public void testFindAll2(){
String url = "http://localhost:7778/user";
//1 创建对象
RestTemplate restTemplate = new RestTemplate();
//2 发送请求并获得数据
ResponseEntity>> entity = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>>() {});
//3 获得响应,并打印
BaseResult> baseResult = entity.getBody();
List data = baseResult.getData();
for (User user : data) {
System.out.println(user);
}
}
@Test
public void testAdd(){
String url = "http://localhost:7778/user";
RestTemplate restTemplate = new RestTemplate();
User user = new User(1,"jack","1234",18);
ResponseEntity entity = restTemplate.postForEntity(url ,user , BaseResult.class);
System.out.println(entity.getStatusCode());
System.out.println(entity.getBody());
}
@Test
public void testUpdate(){
String url = "http://localhost:7778/user";
RestTemplate restTemplate = new RestTemplate();
User user = new User(1,"jack","1234",18);
restTemplate.put(url ,user);
System.out.println("修改成功");
}
@Test
public void testDelete(){
String url = "http://localhost:7778/user/1";
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(url);
System.out.println("删除成功");
}
基于spring boot 测试启动器,自动开启日志输出
spring boot 默认采用logback 进行日志管理的
如何管理日志输出:关闭日志输出
在resources/logback.xml
分析
使用HttpClients.custom()可以构建自定义 CloseableHttpClient 对象
setConnectionManager 用于配置连接
setDefaultRequestConfig 用于配置请求
通过PoolingHttpClientConnectionManager 可以为连接配置连接数和并发数
通过 RequestConfig.custom() 可以配置各种超时时间
代码
@Test
public void testDemo01() throws IOException {
//1 配置连接管理
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 1.1 设置最大连接数
connectionManager.setMaxTotal(1000);
// 1.2 设置并发访问数
connectionManager.setDefaultMaxPerRoute(20);
//2 请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1000)
.setConnectionRequestTimeout(500)
.setSocketTimeout(10 * 1000)
.build();
// 3 获得工具类
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
//重定向策略
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
// 4 发送请求
CloseableHttpResponse response = null;
try {
HttpGet httpGet = new HttpGet("http://localhost:7778/user");
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
response.close();
}
}
SpringBoot官方并没有对HttpClient的启动器。所以我们需要自己完成配置
步骤一:修改yml文件,添加连接池配置
# http配置
http:
maxTotal: 300
defaultMaxPerRoute: 50
connectTimeout: 1000
connectionRequestTimeout: 500
socketTimeout: 5000
package com.czxy.config;
import lombok.Setter;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "http")
@Setter
public class HttpConfig {
private Integer maxTotal;
private Integer defaultMaxPerRoute;
private Integer connectTimeout;
private Integer connectionRequestTimeout;
private Integer socketTimeout;
private Integer staleConnectionCheckEnabled;
@Bean
public PoolingHttpClientConnectionManager connectionManager(){
//1 配置连接管理
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 1.1 设置最大连接数
connectionManager.setMaxTotal(maxTotal);
// 1.2 设置并发访问数
connectionMan1ager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return connectionManager;
}
@Bean
public RequestConfig requestConfig(){
//2 请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout)
.build();
return requestConfig;
}
@Bean
public HttpClient httpClient(HttpClientConnectionManager connectionManager, RequestConfig requestConfig){
// 3 获得工具类
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
//重定向策略
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
return httpClient;
}
}
package com.czxy;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpApplication.class)
public class TestBootHttp {
@Resource
private HttpClient httpClient;
@Test
public void testDemo01() throws IOException {
String url = "http://localhost:7778/user";
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String str = EntityUtils.toString(response.getEntity());
System.out.println(str);
}
}
}
package com.czxy.config;
import lombok.Setter;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.List;
/**
* @author 桐叔
* @email [email protected]
*/
@Configuration
@ConfigurationProperties(prefix = "http")
@Setter
public class HttpConfig {
private Integer maxTotal;
private Integer defaultMaxPerRoute;
private Integer connectTimeout;
private Integer connectionRequestTimeout;
private Integer socketTimeout;
private Integer staleConnectionCheckEnabled;
@Bean
public PoolingHttpClientConnectionManager connectionManager(){
//1 配置连接管理
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 1.1 设置最大连接数
connectionManager.setMaxTotal(maxTotal);
// 1.2 设置并发访问数
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return connectionManager;
}
@Bean
public RequestConfig requestConfig(){
//2 请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout)
.build();
return requestConfig;
}
@Bean
public HttpClient httpClient(HttpClientConnectionManager connectionManager, RequestConfig requestConfig){
// 3 获得工具类
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
//重定向策略
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
return httpClient;
}
@Bean
public ClientHttpRequestFactory requestFactory(HttpClient httpClient ){
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
RestTemplate template = new RestTemplate(requestFactory);
//乱码处理
List> list = template.getMessageConverters();
for (HttpMessageConverter> mc : list) {
if (mc instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
}
}
return template;
}
}
package com.czxy;
import com.czxy.domain.User;
import com.czxy.vo.BaseResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpApplication.class)
public class TestBootRest {
@Resource
private RestTemplate restTemplate;
@Test
public void testAdd(){
String url = "http://localhost:7778/user";
User user = new User(1,"jack","1234",18);
ResponseEntity entity = restTemplate.postForEntity(url ,user , BaseResult.class);
System.out.println(entity.getStatusCode());
System.out.println(entity.getBody());
}
}
CREATE TABLE t_user(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
`password` VARCHAR(32),
age INT
);
INSERT INTO t_user(uid,username,`password`,age) VALUES(1,'jack','1234',18);