共计 1857 个字符,预计需要花费 5 分钟才能阅读完成。
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(); | |
} | |
} |
基于 Spring Boot 2.7、Spring Cloud 2021 & Alibaba、SAS OAuth2 一个可反对企业各业务零碎或产品疾速开发实现的开源微服务利用开发平台
正文完
发表至: springboot
2022-12-01