Microservices + springcloud + springcloud alibaba study notes [Use of OpenFeign] (5/9)

In the previous chapter, it was mentioned that the Ribbon was stopped and stopped. OpenFeign is a further simplification and encapsulation of the Ribbon (interface + annotation)

1. Introduction to OpenFeign

1.1. Concept and function of Feign and OpenFeign

Feign is a declarative web client. It only needs to create an interface and add annotations to complete the call between microservices; using Feign can make writing web service clients easier.

It works by defining a service interface and then adding annotations on it. feign also supports pluggable encoders and decoders. Spring Cloud encapsulates Feign to support Spring MVC standard annotations and Http MessageConverters. Feign can be used in combination with Eureka and Ribbon to support load balancing.

Feign integrates Ribbon and RestTemplate to implement load-balanced execution of Http calls, but encapsulates the original method (Ribbon+RestTemplate), developers do not need to manually use RestTemplate to call services, but define an interface, in this interface The service call can be completed by annotating an annotation, which is more in line with the purpose of interface-oriented programming and simplifies development.
insert image description here

That is, if A wants to call B, Feign is to create an interface in A that is exactly the same as B's external service. We can call this interface to serve B.

1.2, the difference between Feign and OpenFeign

insert image description here

2. OpenFeign usage steps

2.1. Create Feign consumer-side microservices

The project module name is: Cloud-order-feign80

2.2. Modify the POM file configuration

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud2023</artifactId>
        <groupId>com.tigerhhzz.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Cloud-order-feign80</artifactId>

    <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.uclass.springcloud</groupId>
            <artifactId>Api-Commons</artifactId>
            <version>1.0-SNAPSHOT</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>

</project>

</project>

Check the project dependencies, you can see: openfeign inherits the ribbon by nature, and also has the load balancing capability of the ribbon.
insert image description here

2.3, write yml configuration file

server:
  port: 80

spring:
  application:
    name: Cloud-consumer-feign-order80

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #      defaultZone: http://localhost:7001/eureka/   #单机版
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/   #集群版

2.4, write the main startup class

Add the @EnableFeignClients annotation to the class to indicate the Feign client

package com.tigerhhzz.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@Slf4j
@EnableFeignClients     //激活对Feign的使用
@SpringBootApplication
public class OrderFeignMain80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderFeignMain80.class, args);
        log.info("OrderFeignMain80启动成功~~~~~~~~~~~~~~~~~~~");
    }
}

2.5, write business class

Business logic interface + @FeignClient annotation configuration calls provider8001 or 8002 service.

2.5.1. Write the service layer interface for remote invocation of the service provider interface

Service layer: Pay attention to add the @FeignClient(value = "cloud-payment-service") annotation, where the value value indicates the name of the microservice that needs to be called remotely.

package com.tigerhhzz.springcloud.service;

import com.tigerhhzz.springcloud.entities.CommonResult;
import com.tigerhhzz.springcloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author tigerhhzz
 * @date 2023/4/11 15:27
 */

@Component
@FeignClient(value = "cloud-provider-service")   //需要寻找的微服务名称
public interface PaymentFeignService {
    
    

    @GetMapping(value = "/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
2.5.2. Write the controller layer for url mapping and service calling
package com.tigerhhzz.springcloud.controller;

import com.tigerhhzz.springcloud.entities.CommonResult;
import com.tigerhhzz.springcloud.entities.Payment;
import com.tigerhhzz.springcloud.service.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderFeignController {
    
    

    @Resource
    private PaymentFeignService paymentFeignService;
 
    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
    
    
        return paymentFeignService.getPaymentById(id);

    }
}

Note: After the 80 module is started, the client access address is /consumer/payment/get/{id}, first find the PaymentFeignService interface written in the access interface layer 2.5.1, and use the annotation @FeignClient(value = "cloud-provider -service") Go to the Eureka registry to find the microservice interface with the service name "cloud-provider-service". Its call interface is @GetMapping(value = "/payment/{id}" exposed to the outside world provided by the 8001 module ) interface; there is a layer of openfeign interface in the middle.

2.6. Test

Access the interface and test the load balancing function of openfeign.

  1. Start two Eureka clusters 7001/7002 first
  2. Start 2 more microservices 8001/8002
  3. Start the OpenFeign module OrderFeignMain80
  4. Access address: http://localhost/consumer/payment/get/1

Feign uses ribbon to achieve load balancing by default, and gets the result (Feign comes with load balancing configuration items)
insert image description here

3. OpenFeign timeout mechanism

3.1, timeout situation

OpenFeign's default waiting time is 1 second, if it exceeds 1 second, an error will be reported directly

3.2. Set the timeout period

In the application.yaml configuration file, set the timeout period:

#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
# 表示建立连接后从服务器读取到可用资源,所用时间
 ReadTimeout:  5000
# 表示建立连接时间,适用于网络正常的情况下,两端连接所用时间
 ConnectTimeout: 5000

Because the bottom layer of OpenFeign is the ribbon for load balancing, its timeout period is controlled by the ribbon.

4. OpenFeign log printing

insert image description here

Monitor and output the call status of Feign interface, adjust the log level through configuration, so as to understand the details of Http requests in Feign.

4.1, log level

  • NONE: default, do not display any logs
  • BASIC: Only record the request method, URL, response status code and execution time
  • HEADERS: In addition to the information defined in BASIC, there are request and response header information
  • FULL: In addition to the information defined in HEADERS, the body and metadata of the request and response

4.2. Logs using OpenFeign:

Realize adding OpenFeign's log class in the configuration class

Note: Logger is introduced under the import feign.Logger package

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

4.3. Set the log level for the specified class

The Feign client that needs to open the log in the YML file

logging:
 level:
  #feign日志以什么级别监控哪个接口
  com.uclass.springcloud.service.PaymentFeignService: debug

4.4, print results

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43025151/article/details/130078429