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 客戶端實現(xiàn)我們就可以在 java 中像調用一個本地方法一樣完成一次 http 請求,大大減少了編碼成本,同時提高了代碼可讀性。
舉個例子,如果想調用 /tenants 的接口,只需要定義如下的接口類即可
public interface TenantClient {
@GetExchange("/tenants")
Flux<User> getAll();
}Spring 會在運行時提供接口的調用的具體實現(xiàn),如上請求我們可以如 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 實現(xiàn),所以依賴中我們需要添加 webflux

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.
3. 注入聲明式客戶端
通過給 HttpServiceProxyFactory 注入攜帶目標接口 baseUrl 的的 webclient,實現(xiàn) webclient 和 http interface 的關聯(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);
}4. 單元測試調用 http interface
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DemoApi demoApi;
@Test
void testDemoApi() {
demoApi.list();
}
}到此這篇關于SpringBoot 3.0 新特性,內置聲明式HTTP客戶端的文章就介紹到這了,更多相關SpringBoot 聲明式HTTP客戶端內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決spring-boot 打成jar包后 啟動時指定參數(shù)無效的問題
這篇文章主要介紹了解決spring-boot 打成jar包后 啟動時指定參數(shù)無效的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
IntelliJ IDEA安裝插件阿里巴巴Java開發(fā)手冊(Alibaba Java Coding Guidelines
這篇文章主要介紹了IntelliJ IDEA安裝插件阿里巴巴Java開發(fā)手冊(Alibaba Java Coding Guidelines),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
解決mybatis執(zhí)行SQL語句部分參數(shù)返回NULL問題
這篇文章主要介紹了mybatis執(zhí)行SQL語句部分參數(shù)返回NULL問題,需要的的朋友參考下吧2017-06-06
SpringCloud中的分布式鎖用法示例詳解(Java+Redis SETNX命令)
在Spring Cloud項目中,使用Java和Redis結合實現(xiàn)的分布式鎖可以確保訂單的一致性和并發(fā)控制,分布式鎖的使用能夠在多個實例同時提交訂單時,僅有一個實例可以成功進行操作,本文給大家介紹Spring,Cloud中的分布式鎖用法詳解(Java+Redis SETNX命令),感興趣的朋友一起看看吧2023-10-10

