Springboot3.4.x中的RestClient 和 RestTemplate

前言

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版本迭代之后,提供了许多优秀的新属性,如果升级版本之后,有兴趣可以使用

相关推荐
Fency咖啡11 分钟前
Spring 基础核心 - SpringMVC 入门与请求流程
java·后端·spring·mvc
FrankYoou33 分钟前
Spring Boot 自动配置之 Spring transaction
java·spring boot·spring
珹洺1 小时前
Java-Spring 入门指南(十六)SpringMVC--RestFul 风格
java·spring·restful
卷Java1 小时前
饼状图修复总结
java·spring boot·uni-app·echarts
阑梦清川1 小时前
深入理解文件系统和软硬链接
后端
Cache技术分享1 小时前
204. Java 异常 - Error 类:表示 Java 虚拟机中的严重错误
前端·后端
闲人编程2 小时前
使用Django从零开始构建一个个人博客系统
后端·python·django·接口·restful·web·个人博客
做运维的阿瑞2 小时前
从入门到精通:Django的深度探索之旅
开发语言·后端·python·系统架构·django
Penge6662 小时前
Go语言中的切片展开操作符 ...
后端·go
用户4099322502123 小时前
银行转账不白扣钱、电商下单不超卖,PostgreSQL事务的诀窍是啥?
后端·ai编程·trae