http接口从Spring6和SpringBoot3开始,Spring框架支持将远程HTTP服务代理到带有特定注解的Javahttp接口中。OpenFeign和Retrofit等类似的库仍然可以使用,但是http接口增加了对Spring框架的内置支持。什么是声明式客户端?声明式http客户端旨在使编写javahttp客户端更容易。为了实现这个理念,采用了通过处理注解(官方叫declarativeandtemplated)自动生成请求的方式。通过声明式http客户端的实现,我们可以像调用本地方法一样在java中完成一次http请求,大大降低了编码成本,提高了代码的可读性。比如要调用/tenants接口,只需要定义如下接口类publicinterfaceTenantClient{@GetExchange("/tenants")FluxgetAll();}Spring会在运行时提供该接口调用的具体实现,如上要求,我们可以调用@AutowiredTenantClienttenantClient;tenantClient.getAll().subscribe();测试使用1.Maven依赖org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-webflux如下图:目前官方只提供非http接口实现-blockingwebclient,所以我们需要在依赖中添加webflux2。创建Http接口类型需要在接口类中添加@HttpExchange来声明http接口端点这样的东西@HttpExchangepublicinterfaceDemoApi{@GetExchange("/admin/tenant/list")Stringlist();该方法支持以下注解@GetExchange:用于HTTPGET请求。@PostExchange:用于HTTPPOST请求。@PutExchange:用于HTTPPUT请求。@DeleteExchange:用于HTTPDELETE请求。@PatchExchange:用于HTTPPATCH请求。方法参数支持的注解@PathVariable:占位符参数。@RequestBody:请求体。@RequestParam:请求参数。@RequestHeader:请求头。@RequestPart:表单请求。@CookieValue:请求cookie。2.注入声明式客户端通过将目标接口baseUrl的webclient注入HttpServiceProxyFactory,实现webclient与http接口的关联@BeanDemoApidemoApi(){WebClientclient=WebClient.builder().baseUrl("http://pigx.pigx.vip/“)。建造();HttpServiceProxyFactoryfactory=HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();返回factory.createClient(DemoApi.class);}3。单元测试调用httpinterface@SpringBootTestclassDemoApplicationTests{@AutowiredprivateDemoApidemoApi;@TestvoidtestDemoApi(){demoApi.list();}}基于SpringBoot2.7,SpringCloud2021&Alibaba,SASOAuth2开源的微服务应用开发平台,可以支持企业各种业务系统或产品的快速开发和实施