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

相关推荐
在努力的前端小白2 小时前
Spring Boot 敏感词过滤组件实现:基于DFA算法的高效敏感词检测与替换
java·数据库·spring boot·文本处理·敏感词过滤·dfa算法·组件开发
bobz9653 小时前
小语言模型是真正的未来
后端
DevYK4 小时前
企业级 Agent 开发实战(一) LangGraph 快速入门
后端·llm·agent
一只叫煤球的猫5 小时前
🕰 一个案例带你彻底搞懂延迟双删
java·后端·面试
冒泡的肥皂5 小时前
MVCC初学demo(一
数据库·后端·mysql
颜如玉6 小时前
ElasticSearch关键参数备忘
后端·elasticsearch·搜索引擎
卡拉叽里呱啦7 小时前
缓存-变更事件捕捉、更新策略、本地缓存和热key问题
分布式·后端·缓存
David爱编程7 小时前
线程调度策略详解:时间片轮转 vs 优先级机制,面试常考!
java·后端
码事漫谈8 小时前
C++继承中的虚函数机制:从单继承到多继承的深度解析
后端
阿冲Runner8 小时前
创建一个生产可用的线程池
java·后端