http interface
從 Spring 6 和 Spring Boot 3 開始,Spring 框架支持將遠(yuǎn)程 HTTP 服務(wù)代理成帶有特定注解的 Java http interface。類似的庫,如 OpenFeign 和 Retrofit 仍然可以使用,但 http interface 為 Spring 框架添加內(nèi)置支持。
什么是聲明式客戶端
聲明式 http 客戶端主旨是使得編寫 java http 客戶端更容易。為了貫徹這個理念,采用了通過處理注解來自動生成請求的方式(官方稱呼為聲明式、模板化)。通過聲明式 http 客戶端實現(xiàn)我們就可以在 java 中像調(diào)用一個本地方法一樣完成一次 http 請求,大大減少了編碼成本,同時提高了代碼可讀性。
- 舉個例子,如果想調(diào)用 /tenants 的接口,只需要定義如下的接口類即可
public interface TenantClient {
@GetExchange("/tenants")
Flux<User> getAll();
}
Spring 會在運(yùn)行時提供接口的調(diào)用的具體實現(xiàn),如上請求我們可以如 Java 方法一樣調(diào)用
@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 實現(xiàn),所以依賴中我們需要添加 webflux
文章來源:http://www.zghlxwxcb.cn/news/detail-428470.html
2. 創(chuàng)建 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.
- 方法參數(shù)支持的注解
@PathVariable: 占位符參數(shù).
@RequestBody: 請求body.
@RequestParam: 請求參數(shù).
@RequestHeader: 請求頭.
@RequestPart: 表單請求.
@CookieValue: 請求cookie.
2. 注入聲明式客戶端
- 通過給 HttpServiceProxyFactory 注入攜帶目標(biāo)接口 baseUrl 的的 webclient,實現(xiàn) webclient 和 http interface 的關(guān)聯(lián)
@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. 單元測試調(diào)用 http interface
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DemoApi demoApi;
@Test
void testDemoApi() {
demoApi.list();
}
}
基于Spring Boot 2.7、 Spring Cloud 2021 & Alibaba、 SAS OAuth2 一個可支持企業(yè)各業(yè)務(wù)系統(tǒng)或產(chǎn)品快速開發(fā)實現(xiàn)的開源微服務(wù)應(yīng)用開發(fā)平臺文章來源地址http://www.zghlxwxcb.cn/news/detail-428470.html
到了這里,關(guān)于SpringBoot 3.0 新特性,內(nèi)置聲明式HTTP客戶端的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!