What is Spring Cloud Square
When talking about Spring Cloud ecology, you must be familiar with Feign. As shown in the figure below, Feign can hide the Rest requests of the underlying (okhttp, httpclient) and pretend to be similar to the Controller of spring MVC. You don't have to splice URLs, splice parameters and other operations by yourself. Let Feign do everything. Using Feign to call API is like calling local methods, which avoids the tedious task of parsing / encapsulating json data when calling the target microservice.
Spring Cloud Square The project aims to replace the original Spring Cloud Feign and realize cross service invocation by encapsulating the underlying communication class library with Retrofit. At present, it has been incubated in the spring cloud incubator (the last spring cloud loadbalancer incubated in the incubator has officially replaced Ribbon as the officially recommended component).
Before understanding Spring Cloud Square, you need to understand the following components:
-
OkHttp is a third-party class library about network request, which encapsulates the bottom implementation of get, post and other operations of network request. It is one of the most popular network request frameworks at present.
-
Retrofit is a RESTful HTTP network request framework based on OkHttp. It configures network parameters through annotations, supports the parsing and serialization of a variety of data (Gson, Json, Xml, etc.), and also supports RxJava.
Then the service call based on Spring Cloud Square can be abstracted as shown in the following figure:
Get started quickly
Add dependency
- Since spring cloud square has not been officially released at present, the spring maven warehouse needs to be configured.
<repositories> <repository> <id>spring-milestones</id> <url>https://repo.spring.io/milestone</url> </repository> </repositories>
- maven dependency
<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> <!--Add load balancing support--> <dependency> <groupid>org.springframework.cloud</groupid> <artifactid>spring-cloud-starter-loadbalancer</artifactid> </dependency>
Code configuration
@Bean @LoadBalanced public OkHttpClient.Builder okHttpClientBuilder() { return new OkHttpClient.Builder(); }
Code call
- Like the earliest ribbon call, it is very simple.
@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(); }
Advanced use
As an alternative to Spring Cloud Feign, square also supports the form of declarative client. Note that the following code tastes the same as feign
Add dependency
<dependency> <groupid>org.springframework.cloud</groupid> <artifactid>spring-cloud-square-retrofit</artifactid> <version>${square.version}</version> </dependency>
Claim calling client
@RetrofitClient("square-provider") public interface DemoService { @GET("/") Call<string> req(); }
Turn on client scan
@EnableRetrofitClients
Code call
@Autowired DemoService demoService; @SneakyThrows @GetMapping("/retrofit") public String retrofit(){ return demoService.req().execute().body(); }
Simplify it
Retrofit we can add extensions to process the results (the code is provided by Chunge):
/** * The processor returned by the original type, and the default Call is removed * * @author L.cm */ @Configuration(proxyBeanMethods = false) public class ApiCallAdapterFactory extends CallAdapter.Factory { @Override public CallAdapter<!--?, ?--> get(@Nonnull Type returnType, @Nonnull Annotation[] annotations, @Nonnull Retrofit retrofit) { return new CallAdapter<>() { @Override public Type responseType() { return returnType; } @Override public Object adapt(@Nonnull Call<object> call) { try { return call.execute().body(); } catch (IOException e) { // Customize the fallback or throw it directly to the global exception handler return null; } } }; } }
Then the above code can be simplified as follows:
@RetrofitClient("square-provider") public interface DemoService { @GET("/req") String req(); }
@Autowired DemoService demoService; @SneakyThrows @GetMapping("/retrofit") public String retrofit(){ return demoService.req(); }
summary
-
- Since spring cloud square is directly implemented based on retrofit, the overall source code is very simple. It is recommended that you read it.
-
- The implementation of fallback is not implemented in the current version.
-
- The supporting code of this paper https://github.com/lltx/spring-cloud-square-demo </object></string>