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 办法一样调用

@AutowiredTenantClient 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 端点
@HttpExchangepublic 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

@SpringBootTestclass DemoApplicationTests {    @Autowired    private DemoApi demoApi;    @Test    void testDemoApi() {        demoApi.list();    }}
基于Spring Boot 2.7、 Spring Cloud 2021 & Alibaba、 SAS OAuth2 一个可反对企业各业务零碎或产品疾速开发实现的开源微服务利用开发平台