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

相关推荐
加瓦点灯23 分钟前
什么?工作五年还不了解SafePoint?
后端
fictionist27 分钟前
动态 Web 开发技术入门篇
java·服务器·开发语言·笔记·学习·mysql·spring
他日若遂凌云志1 小时前
Lua 模块系统的前世今生:从 module () 到 local _M 的迭代
后端
David爱编程1 小时前
Docker 安全全揭秘:防逃逸、防漏洞、防越权,一篇学会容器防御!
后端·docker·容器
小码编匠1 小时前
WinForm 工业自动化上位机通用框架:注册登录及主界面切换实现
后端·c#·.net
weixin_483745621 小时前
Springboot项目的目录结构
java·后端
阿里云云原生1 小时前
2025年第二届“兴智杯”智能编码创新应用开发挑战赛正式启动
后端
米奇找不到妙妙屋2 小时前
部分请求报 CROS ERROR
spring boot·vue
保持学习ing2 小时前
SpringBoot 前后台交互 -- CRUD
java·spring boot·后端·ssm·项目实战·页面放行
小璐乱撞2 小时前
从原理到实战:基于SpringAI的RAG应用探索
spring·ai编程