OpenFeign service interface call - 2020 latest version of Zhouyang spring cloud (version H & alibaba) learning notes 09

1. General

1.1 what is openfeign

Bottom line: Feign is a declarative Web service client, which makes it very easy to write a Web service client. You just need to create an interface and add annotations to the interface

Feign is a declarative Web Service client. Using feign makes it easier to write Web Service clients.
It is used by defining a service interface and then adding annotations to it. Feign also supports pluggable encoders and decoders.
Spring cloud encapsulates Feign to support Spring MVC standard annotations and HttpMessageConverters
Feign can be used in combination with Eureka and Ribbon to support load balancing

1.2 what can I do

(1) 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 one 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 by 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.

(2) 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

2. Steps for using openfeign

Interface + annotation: microservice calling interface + @ FeignClient

2.1 create a new cloud consumer feign order80 module

Feign is used on the consumer side

2.2 POM

<dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.wang.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--monitor-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--Hot deployment-->
        <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>

2.3 YML

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

2.4 main startup

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class OrderFeifnMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeifnMain80.class,args);
    }
}

2.5 business


(1) Create a new PaymentFeignService interface

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);
}

(2) New FeignOrderController

@RestController
@Slf4j
public class FeignOrderController {

    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }
}

2.6 start up test

Poll Payment1 and payment2. Feign has its own load balancing configuration item
Summary:

3. OpenFeign timeout control

3.1 timeout demonstration

(1) New Payment8001 timeout method

@GetMapping(value = "/payment/feign/timeout")
    public String PaymentFeignTimeout(){
        //Pause the thread for a few seconds
        try{
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return serverport;
    }

(2) Add a call in the order feign module PaymentFeignService

 @GetMapping(value = "/payment/feign/timeout")
    public String PaymentFeignTimeout();

(3) Write the Controller of order feign

@GetMapping(value = "/consumer/payment/feign/timeout")
    public String PaymentFeignTimeout(){
        return paymentFeignService.PaymentFeignTimeout();
    }

(4) Test error

http://localhost/consumer/payment/feign/timeout
OpenFeign will wait for 1 second by default, and an error will be reported after that

3.2 timeout control

Set yml in order feign

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
# Set feign client timeout (OpenFeign supports ribbon by default)
ribbon:
  # It refers to the time taken to establish a connection, which is applicable to the time taken to connect both ends when the network state is normal
  ConnectTimeout: 5000
  # It refers to the time taken to read available resources from the server after the connection is established
  ReadTimeout: 5000

Test and call payment normally.

4. OpenFeign log printing function

Feign provides the log printing function. We can adjust the log level through configuration to understand the details of Http requests in feign. In other words, we can monitor and output the call of feign interface

4.1 log level

  • NONE: by 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.2 configuring log bean s

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

4.3 configuring YML

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
# Set feign client timeout (OpenFeign supports ribbon by default)
ribbon:
  # It refers to the time taken to establish a connection, which is applicable to the time taken to connect both ends when the network state is normal
  ConnectTimeout: 5000
  # It refers to the time taken to read available resources from the server after the connection is established
  ReadTimeout: 5000
logging:
  level:
    # At what level does feign log monitor which interface
    com.wang.springcloud.service.PaymentFeignService: debug

4.4 log viewing

Keywords: OpenFeign

Added by kcgame on Fri, 24 Dec 2021 19:02:13 +0200