Spring Cloud knowledge induction

Spring Cloud knowledge induction


foreword

There are many components involved in Spring Cloud, such as Eureka registration center, remote call, load balancing, microservice fault tolerance mechanism, microservice gateway configuration, microservice link tracking, etc. These components have many versions, and the update iterations are relatively Quick, let’s make a detailed summary of some of the key plug-ins and principles involved.

1. Microservice registration and discovery Eureka

How to configure a microservice registration component? ?

  1. Use Spring Initializar to build the project, mainly select the Eureka Server component in Spring Cloud Discovery (lombok and DevToos are optional), and then build the project.
  2. The annotation @Enable Eureka Server needs to be used in the startup class
  3. configuration file configuration
server:
 port: 9004
spring:
 application:
   name: eureka-server
eureka:
 client:
   service-url:
     # eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址
     defaultZone: http://127.0.0.1:9004/eureka
   # 不注册自己
   register-with-eureka: false
   # 不拉取服务
   fetch-registry: false
  1. Just start the test

Introduced dependencies:

<properties>
      <java.version>1.8</java.version>
      <spring-cloud.version>2020.0.3</spring-cloud.version>
  </properties>
  <dependencies>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      </dependency>
  </dependencies>

  <dependencyManagement>
      <dependencies>
          <dependency>
              <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-dependencies</artifactId>
              <version>${spring-cloud.version}</version>
              <type>pom</type>
              <scope>import</scope>
          </dependency>
      </dependencies>
  </dependencyManagement>

2. Components involved in remote microservice calls

1、RestTemplate

RestTemplate is used to consume REST services, so the main methods of RestTemplate are closely connected with some methods of REST HTTP protocol, such as HEAD, GET, POST, PUT, DELETE, OPTIONS and other methods. The methods corresponding to these methods in the RestTemplate class are headForHeaders(), getForObject(), postForObject(), put(), delete(), etc.

3. Implementation of load balancing LoadBalancer

When injecting the RestTemplate into the Spring container, just add the @LoadBalancer annotation.

The main tool class LoadBlancerClient, LoadBalancerClient can obtain load balancing service provider instance information.

 @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/test-load-balancer")
    public String testLoadBalancer() {
        ServiceInstance instance = loadBalancerClient.choose("cloud-payment-service");
        return instance.getHost() + ":" + instance.getPort();
    }

4. Understanding of OpenFeign

Feign is a declarative HTTP client component, which aims to make writing HTTP clients easier. OpenFeign has added support for Spring MVC annotations and integrated Spring Cloud LoadBalancer and Spring Cloud CircuitBreaker to provide load balancing and circuit breaker functions when using Feign.

5. Microservice Fault Tolerance Resilience4j

General microservices provide four means to achieve fault tolerance

  1. Isolation
    Thread pool isolation, semaphore isolation
  2. Fuse
    CircuitBreaker, the transition between the three states Closed, Open, HalfOpen
  3. Downgrade
    Stop the function of some unimportant services, free up memory and resources to process some important services
  4. Current
    limiting Limit the number of visits within a specified time
    Algorithms involved:
    leaky bucket algorithm, token bucket algorithm, fixed time window algorithm, moving time window algorithm

4.2.1 Introduction to Resilience4j
Netflix's Hystrix microservice fault-tolerant library has stopped updating. It is officially recommended to use Resilience4j instead of Hystrix, or use Spring Cloud Alibaba's Sentinel component.
Resilience4j is a lightweight fault-tolerant framework designed for Java8 and functional programming inspired by Netflix Hystrix. The entire framework just uses Varr's library, and no other external dependencies need to be introduced. In contrast, Netflix Hystrix has a compilation dependency on Archaius, which requires more external dependencies such as Guava and Apache Commons Configuration.
Resilience4j provides a set of high-order functions (decorators), including circuit breakers, current limiters, retry mechanisms, and isolation mechanisms. You can decorate functional interfaces, lambda expressions, or method references with one or more of these decorators. The advantage of this is that you can choose the decorator you want to decorate.
In the process of using Resilience4j, it is not necessary to introduce all dependencies, but only the required dependencies.
Core modules
● resilience4j-circuitbreaker: fuse
● resilience4j-ratelimiter: current limit
● resilience4j-bulkhead: isolation
● resilience4j-retry: automatic retry
● resilience4j-cache: result cache
● resilience4j-timelimiter: timeout processing

6. Microservice Gateway

In the third chapter, we introduced the invocation and load balancing between microservices through Spring Cloud LoadBalancer, and the use of Spring Cloud OpenFeign declarative invocation, so how can our various microservices be provided for external application invocation?
Of course, because it is a REST API interface, there is no problem for external clients to directly call each microservice. But for various reasons, this is not a good choice. Let the client directly communicate with each microservice, there will be the following problems.
● The client will request different microservices multiple times, which increases the complexity of the client.
● There are cross-domain requests, and the processing will become relatively complicated in certain scenarios.
● It is complicated to implement authentication, and each microservice requires independent authentication.
● Difficult to refactor, project iteration may lead to re-partitioning of microservices. If clients communicate directly with microservices, refactoring will be difficult to implement.
● If some microservices use protocols that are unfriendly to firewalls and browsers, direct access will be difficult.
Faced with a problem similar to the above, how do we solve it? The answer is: Service Gateway! In a microservice system, microservice resources are generally not directly exposed to external client access. The advantage of this is to hide internal services to solve the above problems.
The gateway has many important meanings, which are embodied in the following aspects.
● The gateway can do some identity authentication, authority management, and prevent illegal requests to operate services, etc., which can protect services to a certain extent.
● The gateway manages all microservices in a unified manner and exposes them to the outside world. The external system does not need to know the complexity of calling each other in the microservice architecture, and it also avoids the leakage of some sensitive information of internal services.
● Easy to monitor. Monitoring data can be collected at the microservice gateway and pushed to external systems for analysis.
● The client only deals with the service gateway, which reduces the number of interactions between the client and each microservice.
● Multi-channel support, different API service gateways can be provided according to different clients (WEB, mobile, desktop...).
● The gateway can be used for traffic monitoring. Under high concurrency, limit and downgrade the service.
● The gateway separates the service from the internal, which is convenient for testing.
The microservice gateway can realize various functions such as routing and load balancing. Similar to Nginx, reverse proxy function. In the microservice architecture, backend services are often not directly opened to the caller, but routed to the corresponding service through an API gateway according to the requested URL. When the API gateway is added, a wall is created between the third-party caller and the service provider, and permission control is performed in the API gateway, and the API gateway sends the request to the back-end service in a load-balanced manner.

Introduction to Spring Cloud Gateway


SpringCloud Gateway is a brand new project of Spring Cloud. The project is a gateway developed based on technologies such as Spring 5.0, Spring Boot 2.0 and Project Reactor. It aims to provide a simple and effective unified API routing management method for microservice architecture. As a gateway in the Spring Cloud ecosystem, SpringCloud Gateway aims to replace Zuul. In Spring Cloud 2.0 and above, it does not integrate the latest high-performance versions of Zuul 2.0 and above, and still uses the non-Reactor mode before Zuul 2.0. old version of . In order to improve the performance of the gateway, Spring Cloud Gateway is implemented based on the WebFlux framework, and the bottom layer of the WebFlux framework uses the high-performance Reactor mode communication framework Netty. The goal of Spring Cloud Gateway is not only to provide a unified routing method, but also to provide basic functions of the gateway based on the Filter chain, such as: security, monitoring/indicators, and current limiting. Note: The underlying layer of Spring Cloud Gateway uses Netty, a high-performance communication framework.

It mainly involves three parts:
1) Filter (filter):
Similar in concept to Zuul's filter, it can be used to intercept and modify requests, and perform secondary processing on downstream responses. Filters are instances of the org.springframework.cloud.gateway.filter.GatewayFilter class.
(2) Route (routing):
The basic component module of gateway configuration, similar to Zuul's routing configuration module. A Route module is defined by an ID, a target URI, a set of assertions and a set of filters. If the assertion is true, the route matches and the target URI is accessed.
(3) Predicate (assertion):
This is a Java 8 Predicate that can be used to match anything from the HTTP request, such as headers or parameters. The asserted input type is a ServerWebExchange.

Schematic:
insert image description here

Unified cross-domain access issues

A cross-domain request means that the domain where the current request is initiated is different from the domain where the resource pointed to by the request is located. The domain here refers to such a concept: we believe that if the protocol + domain name + port number are the same, then it is the same domain.
For example: if a website with the domain name aaa.cn initiates an Ajax request with the resource path aaa.cn/books/getBookInfo, then this request is in the same domain, because the protocol, domain name and port number of the resource path are the same as The current domain is the same (in the example, the default protocol name is http, and the default port number is 80). However, if you initiate an Ajax request with the resource path bbb.com/pay/purchase, then this request is a cross-domain request, because the domains are inconsistent, and at the same time, due to security issues, this request will be restricted by the same-origin policy

Two common solutions:

  1. Use the annotation @CrossOrigin
  2. How to configure Spring Cloud Gateway
spring:
 cloud:
   gateway:
     globalcors:
       cors-configurations:
         '[/**]':
           allowed-origin-patterns: "*" # spring boot2.4配置
#            allowed-origins: "*"
           allowed-headers: "*"
           allow-credentials: true
           allowed-methods:
             - GET
             - POST
             - DELETE
             - PUT
             - OPTION

7. Spring Cloud Config Configuration Center Components

1. How to configure

  1. Use the Config Server component (under Spring Cloud Config)
  2. Introduce the annotation @EnableConfigServer in the startup class
  3. Configure in the configuration file
server:
 port: 9006
spring:
 application:
   name: cloud-config
 cloud:
   config:
     server:
       git:
         uri: #仓库地址
         search-paths: config
         default-label: master

eureka:
 client:
   service-url:
     defaultZone: http://127.0.0.1:9004/eureka

  1. Create your own configuration repository (created before step 3)

2. Automatic Refresh

  1. Install Rabbitmq and start
  2. Introduce dependencies on the configuration center server
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

  1. Configure the connection to RabbitMQ in application.yml, and configure the exposed /actuator/bus-refresh endpoint at the same time, the code is as follows
spring:
  rabbitmq:
    host: 服务器地址
    port: 5672
    username: rabbitmq 账号
    password: 密码
management:
  endpoints:
    web:
      exposure:
        include: bus-refresh
  endpoint:
    bus-refresh:
      enabled: true  
  1. Configure the client and introduce dependencies
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
 </dependency>
  1. Configure the connection to RabbitMQ in application.yml
spring:
  application:
    name: cloud-payment-service
  rabbitmq:
    host: rabbitmq服务主机地址
    port: 5672
    username: guest
    password: guest
  1. Add annotation to refresh changed configuration @RefreshScope
  2. After modification, you need to use POST request to send a request to (configuration center address/actuator/busrefresh) address before it can be automatically updated. (Only available for post requests)

おすすめ

転載: blog.csdn.net/CXgeng/article/details/123092553