preface

With the installation of the service registry complete, client-side load balancing and service invocation becomes a topic of concern. The Ribbon enables client load balancing, and OpenFeign allows you to program to the interface just like you call the Dubbo interface

Load balancing LB

Load Balance: Simply put, the process of distributing user requests evenly across multiple servers to achieve high availability. Common load balancing tools include NGINx, LVS, and F5 on hardware

Centralized LB

That is, a separate LB facility is used between the consumer and provider of the service, which can be hardware F5, software Nginx, LVS, etc., providing the facility to send the request to the service provider through some policy

The in-process LB

The LB logic is integrated into the consumer, who looks up the list of services from the service registry and then gets the service address to select the appropriate server based on some rule. The Ribbon is an in-process LB. It is a class library that is integrated with the consumer process. The consumer uses the Ribbon to obtain the address of the service provider

Ribbon

SpringCloud Ribbon is a set of client load balancing tools based on Netflix Ribbon. Its main functions are to provide software load balancing algorithms and service invocation for clients. The Ribbon client component provides a wide range of configuration options such as connection timeout and retry. The Ribbon is now in maintenance mode

Version selection

The SpringCloud version depends on the SpringBoot version. You can query the dependency on the SpringBoot version from the official website: spring. IO /projects/sp…

springboot 2.2.5.RELEASE
springcloud Hoxton.SR3
Copy the code

Add the dependent

<! --eureka client--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon-client</artifactId> </dependency> <! -- Or import the Eureka Client directly, which integrates the Ribbon, Hystrix and other Netflix components --> <! --eureka client--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </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.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency>Copy the code

Ribbon Core component Irule

Replace the default load balancing algorithm in the Ribbon

The default load balancing algorithm in the Ribbon is RoundRobinRule

Writing configuration classes

This configuration class cannot be protected from subpackages of the primary launcher class, otherwise the class will be shared by all the Ribbon clients and cannot be customized

@Configuration
public class MyLoadBalance {
    @Bean
    public IRule myRule(a) {
        return newRandomRule(); }}Copy the code

Modifications to the primary boot class

Example Modify the load balancing configuration of a microservice

// Use the @RibbonClient annotation, name property: service name, configuration: custom Irule implementation class
@SpringBootApplication
@EnableEurekaClient
// Customize the load balancing rules for a microservice. Use the @RibbonClient annotation to remove @Configure from the Configuration property and not inject it into the Spring container
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = {MyLoadBalance.class})
public class OrderMain80 {
    public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args); }}Copy the code

Ribbon VS Nginx

Nginx is a load balancer on the server. All requests from clients are sent to Nginx, which distributes the requests to each server. The Ribbon is a local load balancing. When a microservice interface is invoked, the Ribbon will obtain the list of registered service information in the registry and then cache it to the JVM. In this way, the technique of RPC remote service invocation is implemented locally

OpenFeign

Feign is a declarative WebService client. Using Feign makes it easier to write WebService clients. It is used by defining a service interface and adding related annotations. OpenFeign supports SpringMVC standard annotations and HttpMessageConverters. By default, Feign uses the Ribbon to support load balancing

Differences between Feign and OpenFeign

  • Feign is a lightweight Restful HTTP service client in the Spring Cloud component. The Ribbon is built into Feign to load balance clients and invoke services in the service registry. Feign is used by using Feign’s annotation interface, which is invoked to invoke services in the service registry
  • OpenFeign is Spring Cloud’s support for SpringMVC annotations, such as @RequestMapping, on the basis of Feign. OpenFeign’s @FeignClient resolves the interface under SpringMVC’s @RequestMapping annotation and uses dynamic proxies to generate implementation classes that perform load balancing and invoke other services

The invocation of the Feign service

Add interface methods to public modules

// Name attribute: microservice name
@FeignClient(name = "cloud-payment-service")
public interface PaymentService {
    // Service provider configuration
    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getById(@PathVariable("id") Integer id);
    
    @GetMapping("/payment/timeout")
    public String timeout(a);
}
Copy the code

Add the dependent

<! -- Public API dependencies, < <groupId>com.sun</groupId> <artifactId>cloud-api-commons</artifactId> </artifactId> 1.0 the SNAPSHOT < version > < / version > < / dependency > < the 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>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-starter-test</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>Copy the code

Modify the application. Yml

Note: The default timeout time for feign interface calls is 1s. If there is a network delay, the call will fail

server:
  port: 80

spring:
  application:
    name: cloud-consumer-feign-order

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


# OpenFeign timeout handling
feign:
  client:
    config:
      default:
        # refers to the time it takes to establish the connection, which applies to the time it takes for both ends to connect when the network status is normal
        connectTimeout: 5000
        # refers to the time it takes to read the available resources from the server after the connection is established
        readTimeout: 5000
Copy the code

Modify the primary boot class

@SpringBootApplication
@EnableFeignClients
public class OrderOpenFeignMain80 {
    public static void main(String[] args) { SpringApplication.run(OrderOpenFeignMain80.class, args); }}Copy the code

OpenFeign log information improved

The level of logging

  • NONE: The default value. No logs are displayed
  • BASIC: Records only the request method, URL, response status code, and execution time
  • HEADERS: Request and response HEADERS in addition to the information defined in BASIC
  • FULL: In addition to the information defined in HEADERS, the body and metadata of the request and response

Configuring the Log Bean

@Configuration
public class LogConfig {

    @Bean
    Logger.Level feignLoggerLevel(a) {
        returnLogger.Level.FULL; }}Copy the code

Modify the application. Yml

#feign Log print
logging:
  level:
    com.sun.cloud.service.PaymentService: debug
Copy the code