Spring cloud component introduction

Overview of comprehensive application of Spring Cloud system technology

Spring cloud overview

spring Cloud is an implementation framework of microservice architecture

  • The integrated components can have many components; Common components include: eureka registry, Gateway gateway, Ribbon load balancing, Feign service call, and Hystrix fuse. If necessary, add the initiator dependency for the project.
  • Version features: named after English words (name of London Underground Station)

springCloud coordinates

            <!-- springCloud -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
            </dependency>

Service registry eureka

eureka coordinates

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

configuration file

server:
  # The port is set with parameter transmission value; The default 10086 is not used
  port: ${port:10086}

spring:
  application:
    name: eureka_server

eureka:
  client:
    service-url:
      # eureka service address, if it is a cluster; Other cluster eureka addresses need to be specified
      # The port is set with parameter transmission value; Default is not used http://127.0.0.1:10086/eureka
      defaultZone: ${defaultZone:http://127.0.0.1:10086/eureka/}

    # Clusters are needed
    register-with-eureka: false
    # No pull service
    fetch-registry: false
  server:
    # Service failure elimination interval, 60 seconds by default (unit: ms)
    eviction-interval-timer-in-ms: 60000
    # Turn off the self-protection mode (it is turned on by default; that is, the pop-up prompt can be turned off during development)
    enable-self-preservation: false

Service rejection:

When Eureka Client and Eureka Server no longer have heartbeat, Eureka Server will delete the service instance from the service registration list.

Self protection mechanism

Eureka Server will count whether the heartbeat failure rate is lower than 85% within 15 minutes during operation. If it is lower than 85%, Eureka Server will enter the self-protection mechanism.

Self protection mechanism is a mechanism provided to prevent manslaughter services. When the heartbeat of individual clients is lost, it is considered to be the problem of the client, and the client is eliminated; When Eureka captures a large number of heartbeat failures, it is considered that it may be a network problem and enters the self-protection mechanism; When the client's heartbeat recovers, Eureka will automatically exit the self-protection mechanism.

Note: the spingboot startup class must be annotated with @ EnableEurekaServer; Declare the current class as Eureka service.

client

Client coordinates

   </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>

configuration file

server:
  port: 9090

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db2
    username: root
    password: root
  application:
    name: user_service

mybatis:
  type-aliases-package: li.chen.com.user.pojo

# Service registration
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

  instance:
    # Prefer to use ip address instead of host name
    prefer-ip-address: true
    # ip address
    ip-address: 127.0.0.1
    # Renewal interval: 30 seconds by default
    lease-renewal-interval-in-seconds: 5
    # Service failure time: 90 seconds by default
    lease-expiration-duration-in-seconds: 5

Service registration:

Register the service in eureka

Set ip address
Service renewal

Eureka Client will send a heartbeat every 30 seconds to renew the contract. Inform Eureka Server that the Eureka Client is running normally without any problems by renewing the contract.

Service failure:

If Eureka Server does not receive the renewal of Eureka Client within 90 seconds, Eureka Server will delete the instance from its registry.

Note: the spingboot startup class must be annotated with @ EnableEurekaServer; Declare the current class as Eureka service.

Load balancing Ribbon

Ribbon provides two load balancing algorithms: polling and random (polling by default), which can obtain the address from the address list using the load balancing algorithm for service call.

Ribbon load balancing: when the RestTemplate sends a service address request, use the load balancing interceptor to intercept, obtain the service address list according to the service name, and use the ribbon load balancing algorithm to select a service address from the service address list to access the address to obtain service data.

package li.chen.com.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient   //Enable Eureka client discovery
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @Bean
    @LoadBalanced  //Notes on load balancing
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

That is, @ LoadBalanced is used when instantiating RestTemplate, and the service name can be used directly for the service address.

Fuse Hystrix

Fuse mechanism is a microservice link protection mechanism to deal with avalanche effect.

  • Service fuse
    When a microservice of the fan out link is unavailable or the response time is too long, the service will be degraded, which will fuse the call of the microservice of the node and quickly return the "error" response information. When it is detected that the microservice call response of the node is normal, the call link is restored. In the spring cloud framework, the fuse mechanism is implemented through hystrix. Hystrix will monitor the status of calls between microservices. When the failed call reaches a certain threshold, the default is 20 calls in 5 seconds, and the circuit breaker mechanism will be started if the call fails.
    The annotation of fuse mechanism is @ HystrixCommand; And the annotation @ enablercircuitbreaker of the startup class


  • Decoupling and service degradation
    Decoupling does not need to write the corresponding FallBack method for each controller file and each method; The FallBack method is implemented on the direct parent interface. By maintaining it in this way, decoupling can be realized, and the degradation mechanism can be completed by the way.
Component Feign

Integrated ribbon and hystrix functions

Import coordinates

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

The startup class is annotated with @ EnableFeignClients

application.yml main configuration

#ribbon configuration of Feign
ribbon:
  ConnectTimeout: 1000 # Connection timeout duration
  ReadTimeout: 2000 # Data communication timeout duration
  MaxAutoRetries: 0 # Number of retries for the current server
  MaxAutoRetriesNextServer: 0 # How many service retries
  OkToRetryOnAllOperations: false # Do you want to retry all request methods
  #Random strategy
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

#Hytrix configuration for Feign
feign:
  hystrix:
    enabled: true # Turn on the fusing function of Feign
  compression:
    request:
      enabled: true # Turn on request compression
      mime-types: text/html,application/xml,application/json # Set compressed data type
      min-request-size: 2048 # Sets the lower limit of the size that triggers compression
    response:
      enabled: true
      
logging:  #journal
  level:
    li.chen.com.consumer: debug     
  • load balancing
  • Service fuse
  • Request compression
  • log level

Gateway component

The core of Spring Cloud Gateway is a series of filters that can forward client requests to different microservices. Main functions: filtering and routing.

route

coordinate

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

configuration file

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # Routing id, which can be arbitrary
        - id: user-service-route
          # Service address of agent
          #uri: http://127.0.0.1:9090
          # lb means to obtain specific services from eureka (the service name after lb must be registered in eureka before use); Dynamic agent
          uri: lb://UserService
          # Route assertion: can match mapping path
          predicates:
            #-Path = / * * full match
            - Path=/UserController/**

lb means to obtain specific services from eureka (the service name after lb must be registered in eureka before it can be used)
The Gateway directly accesses the user service through the Gateway, so the consumer demo is useless

filter
  • Prefix filter
  • Suffix filter
  • Global filter
Custom filter
  • Custom local filter
    Inherit AbstractGatewayFilterFactory

application.yml configuration

  • Custom global filter
    You don't need to configure yml, just write and inherit GlobalFilter
Load balancing and fuse mechanism

By default, the Gateway integrates Ribbon load balancing and Hystrix circuit breaker mechanism. Refer to the previous configuration

Gateway cross domain configuration

In js request access, if the access address is inconsistent with the domain name, ip or port number of the current server, it is called cross domain request.

  • http://localhost:8080 js in - access - > http://localhost:9091 Because the ports are different, the data is a cross domain request.
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # Routing id, which can be arbitrary
        - id: user-service-route
          # Service address of agent
          #uri: http://127.0.0.1:9090
          # lb means to obtain specific services from eureka; The service name written after lb must be registered in eureka before it can be used
          uri: lb://UserService
          # Route assertion: can match mapping path
          predicates:
            #- Path=/UserController/**
            #- Path=/**
            - Path=/api/UserController/**
          filters:
            #1 means filtering one path, 2 means two paths, and so on
            - StripPrefix=1
            - MyParam=name #Custom filter: Name + GatewayFilterFactory is the class name
            - 
      # Cross domain request
      globalcors:
        corsConfigurations:
          '[/**]':
            #allowedOrigins: * # This way of writing or the following can be used, * means all
            allowedOrigins:
              - "http://docs.spring.io"
            allowedMethods:
              - GET

Can allow from http://docs.spring.io Get the service data through get request.

allowedOrigins: Specifies the server address allowed to access, such as http://docs.spring.io .

'[/ * *]': indicates the address of all requests to access the gateway server

Service registry

Tags: Spring Cloud

Posted by Frango on Thu, 14 Apr 2022 05:35:38 +0930