SpringCloud-2.0 (9. Load balancing - OpenFeign)

Posted by SeaJones on Tue, 22 Feb 2022 10:58:31 +0100

Last: 8 Load balancing - Ribbon

Next: 10 Service degradation - Hystrix - causing problems

Statement: original author: CSDN: Yuan_ four hundred and four

1 . summary

1.1 what is it

Feign also supports pluggable encoders and decoders.

Feign is similar in nature to Open Feign, except that Open Feign is encapsulated by spring cloud to support spring MVC standard annotations and HttpMessageConverters.

  • More for the consumer side, making service calls

1.2 what can I do

What can Feign do

  • Feign aims to make it easier to write Java Http clients.

  • When Ribbon+RestTemplate is used earlier, a set of template calling methods is formed by encapsulating http requests with RestTemplate. However, in the actual development, because there may be more than one invocation of service dependencies, and often an interface will be invoked in multiple places, some client classes are usually encapsulated for each micro service to wrap the invocation of these dependent services.

  • Therefore, Feign made further encapsulation on this basis to help us define and implement the definition of dependent service interfaces. Under the implementation of Feign, we only need to create an interface and configure it in the way of annotation (previously, the Dao interface was marked with Mapper annotation, but now it is a micro service interface marked with Feign annotation), so as to complete the interface binding to the service provider, which simplifies the development of automatically encapsulating the service call client when using the Spring cloud Ribbon.

Feign integrates Ribbon

  • The Ribbon is used to maintain the service list information of Payment, and the load balancing of the client is realized through polling.
  • Unlike Ribbon, Feign only needs to define the service binding interface and implements the service invocation gracefully and simply in a declarative way

1.3 differences between feign and OpenFeign

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

2 . OpenFeign basic use

  1. New module: cloud-consumer-order-Feign-80

  2. Modify POM

     <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
         <dependency>
            <groupId>com.demo.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  3. Write YML

    server:
      port: 80
    
    eureka:
      client:
        register-with-eureka: false
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
    
    
  4. Write the main startup class

    @SpringBootApplication
    // Notes for Feign client
    @EnableFeignClients
    public class FeignMain80 {
        public static void main(String[] args) {
            SpringApplication.run(FeignMain80.class, args);
        }
    }
    
    
  5. Business class

  • Write the business logic interface and call the Provider's service: PaymentFeignService

    // Register components
    @Component
    // Note that this is a Feign interface, and the Value represents the name of the micro service
    @FeignClient(value = "CLOUD-PAYMENT-SERVICE")
    public interface PaymentFeignService {
    	// This access path must as like as two peas of Provider, or Controller.
        @GetMapping("/provider/getPaymentById/{id}")
        public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
    }
    
    

  • Write controller: orderfeigncontroller

    @Slf4j
    @RestController
    @RequestMapping("/consumer")
    public class OrderFeignController {
        @Autowired
        private PaymentFeignService feignService;
    
        @GetMapping("/getPaymentById/{id}")
        public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
            return feignService.getPaymentById(id);
        }
    }
    

3 . Timeout control

3.1 what is it

  • The default Feign client only waits one second
  • If the server processing takes more than 1 second, the Feign client doesn't want to wait and returns an error directly.
  • To avoid this situation, sometimes we need to set the timeout control of Feign client.
  • Open configuration in yml file

3.2 demonstration timeout

  • Deliberately set timeout to demonstrate error conditions
  1. Modify the Controller of Provider - 8001

    Deliberately write a pause statement

    /** Used to test timeout settings */
    @GetMapping(value = "/payment/feign/timeout")
    public String timeOut(){
        // Sleep for 3 seconds
        try { 
            TimeUnit.SECONDS.sleep(3); 
        }catch (Exception e) {
            e.printStackTrace();
        }
        return serverPort;
    }
    
    
  2. Modify the Service of Consumer - Feign - 80

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout();
    
    
  3. Modify the Controller of Consumer - Feign - 80

    @GetMapping(value = "/provider/payment/feign/timeout")
    public String paymentFeignTimeout(){
        return feignService.paymentFeignTimeout();
    }
    
    
  4. Start project test

    First visit the Provider

    Access Consumer

    Prompt timeout

3.3 configure timeout control

  • The timeout control of OpenFeign is actually implemented by Ribbon
  1. Configure YML

    # Set Feign client timeout
    ribbon:
      # The following units are ms and ms
      # It refers to the time taken to establish a connection, which is applicable to the time taken to connect both ends under normal network conditions
      ReadTimeout:  5000
      # It refers to the time taken to read available resources from the server after the connection is established
      ConnectTimeout: 5000
    
    
  2. Restart project test

4 . Log printing function

4.1 what is it

  • Feign provides log printing function
  • We can adjust the log level through configuration to understand the details of Http requests in Feign
  • To put it bluntly, it is to monitor and output the call of Feign interface

4.2 log level

  • 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.

4.3 use

  • Modify cloud-consumer-order-Feign-80
  1. Create Config package and configure log Bean

    @Configuration
    public class FeignConfig {
        @Bean
        Logger.Level feignLoggerLevel(){
            return Logger.Level.FULL;
        }
    }
    
    
  2. Configure YML

    Open Feign client of log in YML

    logging:
      level:
        com.demo.springcloud.service.PaymentFeignService: debug
    
    
  3. test

Topics: Java Load Balance Spring Cloud microservice