Principle and application of openFeign

Posted by Robert Plank on Thu, 20 Jan 2022 01:58:42 +0100

1. Foreword

Earlier, we introduced the soul ferry Nacos in Spring Cloud. Compared with its predecessors, it is not only powerful, but also very simple to deploy.

Today, we will introduce a component of service invocation: OpenFeign, which is also a cruel role beyond its predecessors (Ribbon and Feign).

The article contents are as follows:

2,Feign What is it?

Feign is also a tough role. Feign aims to make Java Http clients easier.

Feign integrates Ribbon . RestTemplate implements load balancing to execute Http calls, but encapsulates the original method (Ribbon+RestTemplate). Instead of manually using RestTemplate to call services, developers define an interface and mark an annotation in this interface to complete service calls, which is more in line with the purpose of interface oriented programming and simplifies development.

Unfortunately, Feign has stopped iterating now. Of course, many enterprises are using Feign now.

Readers who want to learn Feign can learn on the spring Cloud official website. Chen will not introduce it in detail here, which is not the focus of today.

3. What is openFeign?

Feign, which stops iteration, was introduced earlier. To put it simply, OpenFeign is a spring cloud that supports spring MVC annotations based on feign, such as @ RequestMapping. OpenFeign's @ FeignClient can parse the interface under the @ RequestMapping annotation of spring MVC, and generate implementation classes through dynamic proxy load balancing And call other services.

Official website address: https://docs.spring.io/spring-cloud-openfeign/docs/2.2.10.BUILD-SNAPSHOT/reference/html

4. What's the difference between Feign and openFeign?

FeignopenFiegn
Feign is a lightweight RESTful HTTP service client in the spring cloud component. Feign has a built-in Ribbon to do client load balancing and call the services of the service registry. Feign is used by using feign's annotation to define an interface. By calling this interface, you can call the service of the service registryOpenFeign is a spring cloud that supports spring MVC annotations based on Feign, such as @ RequestMapping. OpenFeign's @ FeignClient can parse the interface under the @ RequestMapping annotation of spring MVC, generate implementation classes through dynamic proxy, implement load balancing in the classes and call other services.

5. Environmental preparation

The Spring Cloud version, JDK environment and project environment in this article are the same as those in the previous article Nacos The environment is the same: Fifty five pictures tell you how strong is the soul ferry Nacos of micro service?.

Eureka is no longer used in the registration center. Nacos is directly used as the registration and configuration center. If not, you can view Nacos articles.

The project structure built in this article is shown in the figure below:

The registry uses Nacos to create a micro service, which is a service provider, a product, and a service Consumer.

6. Create service provider

Since microservices call each other, there must be service providers. Create openFeign-provider9005 and register in Nacos. The configuration is as follows:

  
  1. server:
  2.   port:  9005
  3. spring:
  4.   application:
  5.      ##Specify the service name, the name in nacos
  6.     name: openFeign-provider
  7.   cloud:
  8.     nacos:
  9.       discovery:
  10.          #Service address of nacos, IP address in nacos server: port number
  11.         server-addr:  127.0. 0.1: 8848
  12. management:
  13.   endpoints:
  14.     web:
  15.       exposure:
  16.          ##There are special characters in the yml file, which must be contained in single quotation marks, otherwise an error will be reported at startup
  17.          include:  '*'

Note: spring application. The name specified by name will be used in the openFeign interface call.

The project source code will be uploaded. There will be any dependent source code about how to register into Nacos. Combined with Chen's previous Nacos article, it's not difficult!

7. Create a service consumer

Create a new module openFeign-consumer9006 as a consumer service. The steps are as follows.

1. Add dependency

In addition to the dependence of Nacos registry, the dependence of openFeign should also be added, as follows:

  
  1. <dependency>
  2.        <groupId>org.springframework.cloud </groupId>
  3.        <artifactId>spring-cloud-starter-openfeign </artifactId>
  4. </dependency>

2. Add annotation @ EnableFeignClients to enable openFeign function

The old routine. Add an annotation @ EnableFeignClients on the main boot class of Spring boot to enable the openFeign function, as follows:

  
  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @EnableFeignClients
  4. public  class  OpenFeignConsumer9006Application
  5. {
  6.      public  static  void  main( String[] args) {
  7.          SpringApplication. run( OpenFeignConsumer9006Application. class, args);
  8.     }
  9. }

3. New openFeign interface

Create an openFeign interface and annotate it with @ FeignClient annotation, as follows:

  
  1. @FeignClient(value = "openFeign-provider")
  2. public  interface OpenFeignService {
  3. }

Note: the value attribute in the @ FeignClient annotation specifies the service name of the service provider in the nacos registry.

4. Create a new Controller debug

Create a new controller to debug the interface, and directly call the openFeign interface, as follows:

  
  1. @RestController
  2. @RequestMapping("/openfeign")
  3. public  class OpenFeignController {
  4.     
  5. }

Well, so far, an openFeign microservice has been built. It does not realize specific functions. Let's do it a little bit.

8. How does openFeign pass parameters?

There are many ways of interface parameter transfer in development, but there are certain rules for parameter transfer in openFeign, which are described in detail below.

1. Pass JSON data

This is also a common parameter passing rule in interface development. The parameters are identified by @ RequestBody in Spring Boot.

The JSON parameter passing method in the provider interface is as follows:

  
  1. @RestController
  2. @RequestMapping("/openfeign/provider")
  3. public  class OpenFeignProviderController {
  4.      @PostMapping("/order2")
  5.      public Order createOrder2( @RequestBody Order order){
  6.          return order;
  7.     }
  8. }

The parameter code in the openFeign interface of consumer is as follows:

  
  1. @FeignClient(value = "openFeign-provider")
  2. public  interface OpenFeignService {
  3.      /**
  4.      * The parameter is marked with @ RequestBody by default. The @ RequestBody here can be left blank
  5.      * Method name arbitrary
  6.      */
  7.      @PostMapping("/openfeign/provider/order2")
  8.     Order createOrder2( @RequestBody Order order);
  9. }

Note: the default parameter transfer method of openFeign is JSON parameter transfer (@ RequestBody), so the @ RequestBody annotation can not be used when defining the interface, but it is generally filled in for standardization.

2. POJO form transfer parameters

This parameter transfer method is also commonly used. Parameters are received using POJO objects.

Provider service provider code is as follows:

  
  1. @RestController
  2. @RequestMapping("/openfeign/provider")
  3. public  class OpenFeignProviderController {
  4.      @PostMapping("/order1")
  5.      public Order createOrder1(Order order){
  6.          return order;
  7.     }
  8. }

The openFeign code of consumer is as follows:

  
  1. @FeignClient(value = "openFeign-provider")
  2. public  interface OpenFeignService {
  3.      /**
  4.      * The parameter is marked with @ RequestBody by default. If the parameter is passed through the POJO form, it is marked with @ SpringQueryMap
  5.      */
  6.      @PostMapping("/openfeign/provider/order1")
  7.     Order createOrder1( @SpringQueryMap Order order);
  8. }

Many people on the Internet wonder how POJO forms can be transferred. The official document clearly gives the solution, as follows:

openFeign provides an annotation @ SpringQueryMap, which perfectly solves the problem of POJO form parameter transfer.

3. Parameters carried in URL

This method is for GET requests in restful mode, and it is also a common request method.

Provider service provider code is as follows:

  
  1. @RestController
  2. @RequestMapping("/openfeign/provider")
  3. public  class OpenFeignProviderController {
  4.      @GetMapping("/test/{id}")
  5.      public String test( @PathVariable("id")Integer id){
  6.          return  "accept one msg id="+id;
  7. }

The consumer openFeign interface is as follows:

  
  1. @FeignClient(value = "openFeign-provider")
  2. public  interface OpenFeignService {
  3.      @GetMapping("/openfeign/provider/test/{id}")
  4.     String  get( @PathVariable("id")Integer id);
  5. }

It is easy to understand how to use the annotation @ PathVariable to receive placeholders in URLs.

4. Common form parameters

This method is not recommended, but many developers are using it.

Provider service provider code is as follows:

  
  1. @RestController
  2. @RequestMapping( "/openfeign/provider")
  3. public  class  OpenFeignProviderController {
  4.      @PostMapping( "/test2")
  5.      public  String  test2( String id,String name){
  6.          return  MessageFormat. format( "accept on msg id={0},name={1}",id,name);
  7.     }
  8. }

The openFeign interface parameters of consumer consumers are as follows:

  
  1. @FeignClient(value = "openFeign-provider")
  2. public  interface OpenFeignService {
  3.      /**
  4.      * The @ RequestParam annotation must be marked, and the value attribute must be filled with the parameter name
  5.      * The method parameter name can be arbitrary, but the value attribute in the @ RequestParam annotation must be the same as the parameter name in the provider
  6.      */
  7.      @PostMapping("/openfeign/provider/test2")
  8.     String test( @RequestParam("id") String arg1, @RequestParam("name") String arg2);
  9. }

5. Summary

There are many ways to transfer parameters, such as file transfer parameters Chen here just listed four common ways to pass parameters.

9. How to handle timeout?

To understand timeout processing, let's take a look at an example: I sleep the provider service interface for 3 seconds. The interface is as follows:

  
  1. @PostMapping("/test2")
  2. public String test2(String  id,String name) throws InterruptedException {
  3.         Thread.sleep( 3000);
  4.          return MessageFormat. format( "accept on msg id={0},name={1}", id,name);
  5. }

At this time, we call the openFeign interface of consumer, and the returned results are as follows:

It is obvious that the program is abnormal and the interface call timeout is returned. what? why?...........

openFeign actually has a default timeout. The default timeout is 10 seconds for connection and 60 seconds for reading. The source code is in feign. Com Request. Options #options() method, as shown in the following figure:

Then the question comes: why do I report timeout when I only sleep for 3 seconds?

In fact, openFeign integrates Ribbon. The default timeout connection time and read timeout of Ribbon are 1 second. The source code is at org springframework. cloud. openFeign. Ribbon. Feignloadbalancer#execute() method, as shown in the following figure:

If openFeign does not set the corresponding timeout, the default timeout of Ribbon will be used.

After understanding the principle of timeout setting, it is clear that two schemes are generated, as follows:

  • Set the timeout for openFeign

  • Set the timeout for the Ribbon

1. Set the timeout of the Ribbon (not recommended)

The settings are simple. Add the following settings to the configuration file:

  
  1. ribbon :
  2.    #Value is the time taken to establish the link, which is applicable to the time taken by the links at both ends under normal network conditions
  3.   ReadTimeout :  5000
  4.    #It refers to the time taken to read available resources from the server after the link is established
  5.   ConectTimeout :  5000

2. Set the timeout of openFeign (recommended)

openFeign is very simple to set the timeout. You only need to configure it in the configuration file, as follows:

  
  1. feign:
  2.   client:
  3.     config:
  4.       ##  default Set the global timeout. Specify the service name. You can set the timeout of a single service
  5.        default:
  6.         connectTimeout:  5000
  7.         readTimeout:  5000

default sets the global timeout, which is effective for all openFeign interface services

However, normal business logic may involve calls to multiple openFeign interfaces, as shown in the following figure:

The pseudo code in the figure above is as follows:

  
  1. public T invoke(){
  2.      //1. Call serviceA
  3.     serviceA();
  4.     
  5.      //2. Call serviceA
  6.     serviceB();
  7.     
  8.      //3. Call serviceA
  9.     serviceC();
  10. }

Can the global timeout configured above pass? Obviously, serviceA and serviceB can be called successfully, but serviceC cannot be executed successfully. It must report timeout.

At this time, we can configure a separate timeout for serviceC as follows:

  
  1. feign:
  2.   client:
  3.     config:
  4.        ##default: set the global timeout. Specify the service name. You can set the timeout of a single service
  5.        default:
  6.         connectTimeout:  5000
  7.         readTimeout:  5000
  8.        ##Configure the timeout for serviceC service separately
  9.       serviceC:
  10.         connectTimeout:  30000
  11.         readTimeout:  30000

Note: the timeout for a single configuration will override the global configuration.

10. How to enable log enhancement?

Although openFeign provides log enhancement, it does not display any logs by default, but developers can configure the log level themselves in the debugging phase.

The log level of openFeign is as follows:

  • NONE: default, no logs are displayed;

  • BASIC: only record the request method, URL, response status code and execution time;

  • HEADERS: in addition to the information defined in BASIC, there are also header information of request and response;

  • FULL: in addition to the information defined in HEADERS, there are also the body and metadata of the request and response.

The configuration is also very simple. The steps are as follows:

1. Configure the log level in the configuration class

You need to customize a configuration class and set the log level in it, as follows:

Note: the logger here is in feign package.

2. Set interface log level in yaml file

You only need to adjust the interface log level of the specified package or openFeign in the configuration file as follows:

  
  1. logging:
  2.   level:
  3.     cn.myjszl.service: debug

Here's CN myjszl. Service is the package name of the openFeign interface. Of course, you can also configure a specific openFeign interface.

3. Demonstration effect

In the above steps, the log is set to FULL. At this time, a request is issued. The log effect is as follows:

The log details the contents of the request header and request body.

11. How do I replace the default httpclient?

Feign uses the JDK native URLConnection to send HTTP requests by default. There is no connection pool, but a long connection will be maintained for each address, that is, using the HTTP persistence connection.

In the production environment, the default http client is usually not used. There are usually two options:

  • Using Apache httpclient

  • Using OkHttp

As for which is better, in fact, each has its own advantages. I prefer Apache httpclient. After all, the old brand has no problem with stability.

So how to replace it? In fact, it is very simple. The following demonstration uses Apache httpclient instead.

1. Add ApacheHttpClient dependency

Add the following dependencies in the pom file of openFeign interface service:

  
  1. <!--     use Apache HttpClient replace Feign Primordial httpclient-->
  2.      <dependency>
  3.        <groupId>org.apache.httpcomponents </groupId>
  4.        <artifactId>httpclient </artifactId>
  5.      </dependency>
  6.     
  7.      <dependency>
  8.        <groupId>io.github.openfeign </groupId>
  9.        <artifactId>feign-httpclient </artifactId>
  10.      </dependency>

Why add the above dependencies? It's not difficult to see from the source code. Please see org springframework. cloud. openfeign. FeignAutoConfiguration. The code of httpclientfeignconfiguration is as follows:

For the generation conditions in the above red box, @ ConditionalOnClass(ApacheHttpClient.class) must have ApacheHttpClient to take effect, and feign httpclient. Enabled this configuration should be set to true.

2. Open in configuration file

To enable configuration in the configuration file, the code is as follows:

  
  1. feign:
  2.    client:
  3.      httpclient:
  4.        #Open Http Client
  5.        enabled:  true

3. How to verify that the replacement is successful?

It's actually very simple, in feign Synchronousmethodhandler#executeanddecade() can clearly see which client to call, as shown in the following figure:

As you can see in the figure above, the Apache httpclient is finally invoked.

4. Summary

The above steps only demonstrate one alternative scheme, and the remaining one will not be demonstrated. The principle is the same.

12. How to optimize communication?

Before talking about how to optimize, let's take a look at the GZIP} compression algorithm. The concept is as follows:

gzip is a data format, which uses deflate algorithm to compress data; gzip is a popular data compression algorithm, which is widely used, especially on Linux platform.

When GZIP is compressed to a plain text data, the effect is very obvious, and the data size can be reduced by more than 70%.

The compressed network data actually reduces the number of bytes transmitted on the network. The most obvious advantage is that it can speed up the loading of web pages. The benefits of faster web page loading are self-evident. In addition to saving traffic and improving users' browsing experience, another potential benefit is that GZIP has a better relationship with search engine crawling tools. For example, Google can retrieve web pages faster than ordinary manual crawling by directly reading GZIP files.

The principle of GZIP compression transmission is shown in the figure below:

According to the above figure, the disassembly steps are as follows:

  • The client requests the server with the fields: accept encoding: gzip, deflate in the header, indicating to the server the compression format (gzip or deflate) supported by the client. If the header is not sent, the server will not compress.

  • After receiving the request, if the server finds that the request header contains the accept encoding field and supports this type of compression, it will compress the response message and return it to the client, and carry the content encoding: gzip message header, indicating that the response message has been compressed according to this format.

  • After receiving the response, the client first determines whether there is a content encoding header. If so, decompress the message in this format. Otherwise, it shall be handled as normal message.

openFeign supports request / response to enable GZIP compression. The overall process is as follows:

In the above figure, only two pieces of GZIP transmission are involved, namely application client - > application service and application service - > application client.

Note: the GZIP supported by openFeign is only the request and response of the openFeign interface, that is, the openFeign consumer invokes the service provider's interface.

openFeign is also very simple to open GZIP. You only need to open the following configuration in the configuration file:

  
  1. feign:
  2.    ##Turn on compression
  3.   compression:
  4.     request:
  5.       enabled:  true
  6.        ##Turn on the compression threshold, in bytes. The default is 2048, that is, 2k. Here, it is set to 10 bytes for demonstration effect
  7.       min-request-size: 10
  8.       mime-types: text/xml,application/xml,application/json
  9.     response:
  10.       enabled:  true

After the above configuration is completed, send a request, and you can clearly see that GZIP compression has been carried in the request header, as shown in the following figure:

13. How to downgrade?

The common frameworks include Hystrix and Sentinel. By default, openFeign supports Hystrix, which is reflected in the official documents. After all, it is a milk compatriots, ha ha

However, Alibaba Sentinel completely kills Hystrix in terms of functional features, simplicity and ease of use. Therefore, this chapter uses openFeign+Sentinel for integration to realize service degradation.

Note: Sentinel is not introduced here. Chen intends to introduce Sentinel's strengths in detail in the next article.

1. Add Sentinel dependency

Add sentinel dependency in the pom file of openFeign-consumer9006 consumer (because the aggregation module is used, the version number is not specified), as follows:

  
  1. <dependency>
  2.        <groupId>com.alibaba.cloud </groupId>
  3.        <artifactId>spring-cloud-starter-alibaba-sentinel </artifactId>
  4. </dependency>

2. Enable sentinel in configuration file

To use the downgrade function of sentinel in openFeign, you need to open it in the configuration file and add the following configuration:

  
  1. feign:
  2.   sentinel:
  3.     enabled:  true

3. Add demotion callback class

This class must implement the same class as the openFeign interface, as shown in the following figure:

OpenFeignFallbackService is a degraded callback class. Once an exception occurs in the corresponding interface in OpenFeignService, the corresponding method in this class will be called for degradation processing.

4. Add fallback attribute

Add the fallback attribute in @ FeignClient. The attribute value is the class of degraded callback, as follows:

  
  1. @FeignClient(value = "openFeign-provider",fallback = OpenFeignFallbackService.class)
  2. public  interface OpenFeignService {}

5. Demonstration

After the above four steps, the fuse degradation of openFeign has been set. At this time, the effect is demonstrated.

Via postman call http://localhost:9006/openfeign/order3 The normal logic return of this interface is shown in the figure below:

Now create an exception manually and throw an exception in the interface provided by the service, as shown in the following figure:

Call again at this time http://localhost:9006/openfeign/order3 , return as shown in the figure below:

Oh, you can clearly see that the service has been successfully downgraded and called. Oh, the function is completed.

Note: in the actual development, the returned results should be customized according to the architecture. Chen here is just for the convenience of demonstration, not for reference. Ha ha...

Topics: Java Spring Spring Cloud