Spring Cloud Square 是什么
談起 Spring Cloud 生態(tài)大家一定對 Feign 不陌生,如下圖所示,F(xiàn)eign 可以把底層(okhttp懂衩、httpclient)Rest 的請求進行隱藏脯倒,偽裝成類似 SpringMVC 的 Controller 一樣。你不用再自己拼接 url漱病,拼接參數(shù)等等操作买雾,一切都交給 Feign 去做。使用 Feign 調(diào)用 API 就像調(diào)用本地方法一樣杨帽,從避免了調(diào)用目標(biāo)微服務(wù)時漓穿,需要不斷的解析/封裝 json 數(shù)據(jù)的繁瑣。
Spring Cloud Square 項目旨在替代原有的 Spring Cloud Feign , 借助 Retrofit 對底層通信類庫的封裝實現(xiàn)跨服務(wù)調(diào)用注盈,目前已在 spring-cloud-incubator 孵化器進行孵化 (上一個在孵化器孵化 spring-cloud-loadbalancer 已經(jīng)正式接替 Ribbon 成為正式推薦組件)晃危。
在了解 Spring Cloud Square 之前,需要先了解以下組件:
OkHttp 是一個關(guān)于網(wǎng)絡(luò)請求的第三方類庫老客,其中封裝了網(wǎng)絡(luò)請求的 get僚饭、post 等操作的底層實現(xiàn),是目前最為火熱的網(wǎng)絡(luò)請求框架之一胧砰。
Retrofit 是一個 RESTful 的 HTTP 網(wǎng)絡(luò)請求框架鳍鸵,它是基于 OkHttp 的。它是通過注解配置網(wǎng)絡(luò)參數(shù)的尉间,支持多種數(shù)據(jù)的解析和序列化(Gson偿乖、Json、Xml 等哲嘲,并且對 RxJava 也是支持的贪薪。
那么基于 Spring Cloud Square 的服務(wù)調(diào)用可以抽象成如下圖所示:
快速上手
添加依賴
- 由于目前 spring-cloud-square 未正式發(fā)布,需要配置 spring maven 倉庫眠副。
<repositories>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
- maven 依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-square-okhttp</artifactId>
<version>${square.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<!--添加負(fù)載均衡支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
代碼配置
@Bean
@LoadBalanced
public OkHttpClient.Builder okHttpClientBuilder() {
return new OkHttpClient.Builder();
}
代碼調(diào)用
- 和最早的 ribbon 調(diào)用一樣画切,非常的簡單。
@Autowired
OkHttpClient.Builder builder;
@GetMapping
public String req() {
Request request = new Request.Builder()
.url("http://square-provider/req").build();
Response response = builder.build().newCall(request).execute();
return response.body().string();
}
進階使用
作為 Spring Cloud Feign 的替代品囱怕,square 也支持聲明式客戶端的形式霍弹。注意看以下代碼 和 feign 一樣的味道
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-square-retrofit</artifactId>
<version>${square.version}</version>
</dependency>
聲明調(diào)用客戶端
@RetrofitClient("square-provider")
public interface DemoService {
@GET("/")
Call<String> req();
}
開啟客戶端掃描
@EnableRetrofitClients
代碼調(diào)用
@Autowired
DemoService demoService;
@SneakyThrows
@GetMapping("/retrofit")
public String retrofit(){
return demoService.req().execute().body();
}
總結(jié)
- 由于 spring-cloud-square 直接基于 retrofit 實現(xiàn),整體源碼非常的簡單光涂,推薦大家一讀庞萍。
- 目前版本暫未實現(xiàn) fallback 相關(guān)的實現(xiàn)。