Cloud Native Microservices Chapter 6 Remote Calling and Load Balancing of Spring Cloud Eureka Microservices

Table of Contents of Series Articles

Chapter 1 Application of Java Thread Pool Technology
Chapter 2 Application of CountDownLatch and Semaphone Chapter
3 Introduction to Spring Cloud
Chapter 4 Spring Cloud Netflix - Eureka
Chapter 5 Spring Cloud Netflix - Ribbon
Chapter 6 Spring Cloud - OpenFeign

Insert image description here



Preface

The full name of OpenFeign is Spring Cloud OpenFeign. It is a declarative service calling and load balancing component officially launched by Spring. We can call remote services just like calling local methods without feeling that we are making a remote call at all.
Insert image description here

1. The implementation principle and process of OpenFeign

OpenFeign is a declarative web service client that makes writing web service clients easier. By using OpenFeign, developers can more easily create client code that interacts with remote services.
OpenFeign automatically encapsulates HTTP requests and simplifies the process of remote calling code, allowing developers to focus more on the implementation of business logic, improving development efficiency and code readability.

1.1. OpenFeign supports all annotations in the Spring Cloud system

For example, @GetMapping, @PostMapping, @PathVariable, @RequestParam, etc. Custom annotations are also supported.

1.2. OpenFeign automatically encapsulates HTTP requests

Including HTTP method, request URL, request parameters, request headers, etc., developers do not need to manually write HTTP request code. You only need to define an interface and specify the path and method of the interface through annotations, and OpenFeign will automatically send HTTP requests and parse the response data.

1.3. OpenFeign supports request interceptors and response interceptors

Developers can implement request interceptors and response interceptors to process HTTP requests and responses, such as adding authentication information, retrying, etc.

1.4. Process in Spring project

During the startup of the Spring project, OpenFeign will initiate an active package scanning process. Load all interfaces modified by @FeignClient from the specified directory, convert these interfaces into beans, and hand them over to Spring for management. These interfaces will be parsed by MVC Constract, and the annotations on the methods will be parsed and placed in MethodMetadata. Each FeignClient interface will generate a dynamic proxy object pointing to the HashMap of the MethodHandler containing the method.

1.5. Remote calling

When service A initiates a remote call, it will find an instance of MethodHandler from the dynamic proxy proxy and generate a request, including the requested URL. Find the IP address of a service through the load balancing algorithm and splice the requested URL. Service B processes the remote call initiated by service A, executes the logic, and returns a response to A.

2. Commonly used annotations

When using OpenFegin to make remote service calls, commonly used annotations are as follows.

annotation illustrate
@FeignClient This annotation is used to notify the OpenFeign component to parse the interface under the @RequestMapping annotation, and generate implementation classes through dynamic proxy to achieve load balancing and service invocation.
@EnableFeignClients This annotation is used to enable the OpenFeign function. When the Spring Cloud application starts, OpenFeign will scan the interface marked with the @FeignClient annotation, generate a proxy and register it in the Spring container.
@RequestMapping Spring MVC annotation, use this annotation to map requests in Spring MVC, and use it to specify which URL requests the controller (Controller) can handle, which is equivalent to the configuration of web.xml in Servlet.
@GetMapping Spring MVC annotation is used to map GET requests. It is a combined annotation, equivalent to @RequestMapping(method = RequestMethod.GET).
@PostMapping Spring MVC annotation is used to map POST requests. It is a combined annotation, equivalent to @RequestMapping(method = RequestMethod.POST).

3. Practice

3.1. Modify pom.xml configuration

Based on the previous chapter ["Microservices in Practice" Chapter 5 Spring Cloud Netflix Ribbon ], add OpenFeign dependencies

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.kelvin</groupId>
        <artifactId>SpringCloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>customer-api</artifactId>
    <name>customer-api</name>
    <description>customer-api</description>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--devtools 开发工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--Spring Boot 测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--junit 测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
            <version>1.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
           <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-loadbalancer -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>com.kelvin</groupId>
            <artifactId>common-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

3.2. Add user service interface and FeignClient configuration

import com.kelvin.common.model.UserInfo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;

/***
 * @title 用户服务接口
 * @desctption 用户服务接口
 * @author kelvin
 * @create 2023/5/11 16:44
 **/
@Component
@FeignClient(value = "USER-SERVICE")
public interface UserService {
    
    
    @RequestMapping(value = "/user/userInfoList",method = RequestMethod.GET)
    public List<UserInfo> userInfoList();
}

3.3. Modify the control layer UserConsumerController

import com.kelvin.common.model.UserInfo;
import com.kelvin.customerapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/***
 * @title UserConsumerController
 * @desctption 用户控制层
 * @author kelvin
 * @create 2023/5/11 14:22
 **/
@RestController
@RequestMapping("/user")
public class UserConsumerController {
    
    

/*    @Autowired
    private UserConsumerService userConsumerService;*/

    @Autowired
    private UserService userService;

    @GetMapping("/userInfoList")
    public List<UserInfo> userInfoList(){
    
    
        return userService.userInfoList();
    }
}

3.4. Add OpenFeign configuration to startup class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

/***
 * @title SpringBoot 启动类
 * @desctption SpringBoot 启动类
 * @author kelvin
 * @create 2023/5/11 12:22
 **/
@SpringBootApplication
@EnableFeignClients
public class CustomerApiApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(CustomerApiApplication.class, args);
    }

}

3.5. Remote call timeout setting

openFeign actually has a default timeout. The default connection timeout is 10 seconds and the read timeout is 60 seconds. You
can add configurations to customize the timeout.


server:
  port: 80

eureka:
  client:
    register-with-eureka: false #本微服务为服务消费者,不需要将自己注册到服务注册中心
    fetch-registry: true  #本微服务为服务消费者,需要到服务注册中心搜索服务
    service-url:
      defaultZone: http://localhost:7001/eureka
feign:
  client:
    config:
      default:
        #建立连接所用的时间,适用于网络状况正常的情况下,两端连接所需要的时间
        connect-timeout: 5000
        #指建立连接后从服务端读取到可用资源所用的时间
        read-timeout: 10000

4. Summary

OpenFeign automatically encapsulates HTTP requests and simplifies the process of remote calling code, allowing developers to focus more on the implementation of business logic, improving development efficiency and code readability.

Guess you like

Origin blog.csdn.net/s445320/article/details/130624259