阅读 70

SpringBoot 3.0 新特性,内置声明式 HTTP 客户端

http interface

从 Spring 6 和 Spring Boot 3 开始,Spring 框架支持将远程 HTTP 服务代理成带有特定注解的 Java http interface。类似的库,如 OpenFeign 和 Retrofit 仍然可以使用,但 http interface 为 Spring 框架添加内置支持。

什么是声明式客户端

声明式 http 客户端主旨是使得编写 java http 客户端更容易。为了贯彻这个理念,采用了通过处理注解来自动生成请求的方式(官方称呼为声明式、模板化)。通过声明式 http 客户端实现我们就可以在 java 中像调用一个本地方法一样完成一次 http 请求,大大减少了编码成本,同时提高了代码可读性。

  • 举个例子,如果想调用 /tenants 的接口,只需要定义如下的接口类即可

public interface TenantClient {   @GetExchange("/tenants")   Flux<User> getAll(); } 复制代码

Spring 会在运行时提供接口的调用的具体实现,如上请求我们可以如 Java 方法一样调用

 @Autowired TenantClient tenantClient; tenantClient.getAll().subscribe( ); 复制代码

测试使用

1. maven 依赖

<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- For webclient support --> <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-webflux</artifactId> </dependency> 复制代码

如下图: 目前官方只提供了非阻塞 webclient 的 http interface 实现,所以依赖中我们需要添加 webflux

2. 创建 Http interface 类型

  • 需要再接口类上添加 @HttpExchange 声明此类事 http interface 端点

@HttpExchange public interface DemoApi {     @GetExchange("/admin/tenant/list")     String list(); 复制代码

  • 方法上支持如下注解

@GetExchange:  for HTTP GET requests. @PostExchange:  for HTTP POST requests. @PutExchange: for HTTP PUT requests. @DeleteExchange: for HTTP DELETE requests. @PatchExchange:  for HTTP PATCH requests. 复制代码

  • 方法参数支持的注解

@PathVariable: 占位符参数. @RequestBody: 请求body. @RequestParam: 请求参数. @RequestHeader: 请求头. @RequestPart: 表单请求. @CookieValue: 请求cookie. 复制代码

2. 注入声明式客户端

  • 通过给 HttpServiceProxyFactory 注入携带目标接口 baseUrl 的的 webclient,实现 webclient 和 http interface 的关联

    @Bean     DemoApi demoApi() {         WebClient client = WebClient.builder().baseUrl("http://pigx.pigx.vip/").build();         HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();         return factory.createClient(DemoApi.class);     } 复制代码

3. 单元测试调用 http interface

 @SpringBootTest class DemoApplicationTests { @Autowired private DemoApi demoApi; @Test void testDemoApi() { demoApi.list(); } }


作者:冷冷zz
链接:https://juejin.cn/post/7172014407247986696

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐