前言
Springboot3.4.x
发布之后,对于RestClient 和 RestTemplate,添加了支持http客户端配置的支持
RestClient等配置
http客户端类型
Springboot3.4.x
新增配置spring.http.client.factory
,支持对http客户端的配置,支持的类型有
java
Apache HTTP Components (HttpComponentsClientHttpRequestFactory)
Jetty Client (JettyClientHttpRequestFactory)
Reactor Netty HttpClient (ReactorClientHttpRequestFactory)
JDK HttpClient (JdkClientHttpRequestFactory)
Simple JDK HttpURLConnection (SimpleClientHttpRequestFactory)
示例
新增一个controller类
typescript
@Slf4j
@RestController
public class HttpController {
@RequestMapping("/hello")
public String hello() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri("http://localhost:8019/test").retrieve().body(String.class);
log.info("返回结果为:{{}}", result);
return "success";
}
@GetMapping("/test")
public String test() {
log.info("info日志");
return "hello";
}
}
application.properties
配置如下
ini
server.port=8019
spring.profiles.active=dev
spring.application.name=demo-rest-client
jdk
配置如下
yaml
spring:
http:
client:
factory: jdk
访问
bash
http://localhost:8019/hello
输出结果
http_components
这个需要加入httpclient5包
xml
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.5</version>
</dependency>
bash
http://localhost:8019/hello
输出结果

jetty
yaml
spring:
http:
client:
factory: jetty
pom.xml
配置加入
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 去除Tomcat容器 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 增加Jetty容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
访问
bash
http://localhost:8019/hello
输出结果

simple
yaml
spring:
http:
client:
factory: simple
使用jdk
默认的HttpURLConnection 访问
bash
http://localhost:8019/hello
输出结果

总结
Springboot3
版本迭代之后,提供了许多优秀的新属性,如果升级版本之后,有兴趣可以使用