SpringCloud learning notes

SpringCloud

Source of notes: spring cloud tutorial in Silicon Valley at station B (the first season of Zhouyang)

1. Microservices

1.1 general

Microservice architecture is a popular architecture idea in recent years.

Microservice architecture is an architecture mode, or architecture style. It advocates dividing a single application into a group of small services. Each service runs in its own independent process. Services coordinate and configure with each other to provide final value for users. Services communicate with each other through lightweight communication mechanism (HTTP), Each service is built around a specific business and can be independently deployed to the production environment. In addition, a unified and centralized service management mechanism should be avoided as far as possible. For a specific service, an appropriate language and tool (Maven) should be selected according to the business context, There can be a very lightweight centralized management to coordinate these services. Services can be written in different languages or different data stores * ***

Understanding microservices from a technical perspective

  • The core of microservicing is to divide the traditional one-stop application into one service according to the business and completely decouple it. Each microservice provides a service with a single business function. One service does one thing. From a technical point of view, it is a small and independent processing process. The concept of similar process can be started or destroyed independently, Have their own independent database.

1.2 microservices and microservice architecture

Microservices

It emphasizes the size of the service. It focuses on a certain point. It is a service application that specifically solves a certain problem / provides landing corresponding services. In a narrow sense, it can be regarded as micro service projects in the IDEA or Moudel. In the IDEA tool, independent small Moudel developed by Maven is used. It specifically uses a small module developed by SpringBoot. Professional things are done by professional modules, and each module does one thing. The emphasis is on individuals, and each individual completes a specific task or function.

Microservice architecture

A new form of architecture was proposed by Martin Fowler in 2014.

Microservice architecture is an architecture model. It advocates dividing a single application into a group of small services, which coordinate and cooperate with each other to provide final value for users. Each service runs in its own independent process. Lightweight communication mechanism (such as HTTP) is adopted between services to cooperate with each other. Each service is built around specific business and can be independently deployed to the production environment. In addition, unified and centralized service management mechanism should be avoided as far as possible. For a specific service, Appropriate languages and tools (such as Maven) should be selected according to the business context to build it

1.3 advantages and disadvantages of microservices

advantage

  • The principle of single responsibility;

  • Each service is cohesive and small enough, and the code is easy to understand, so that it can focus on a specified business function or business requirement;

  • The development is simple and the development efficiency is improved. A service may be dedicated to only one thing;

  • Microservices can be developed independently by a small team, which only needs 2-5 developers;

  • Microservices are loosely coupled and functionally meaningful services, which are independent in both development and deployment stages;

  • Microservices can be developed in different languages;

  • It is easy to integrate with third parties. Microservices allow easy and flexible integration and automatic deployment through continuous integration tools, such as jenkins, Hudson and bamboo;

  • Microservices are easy to be understood, modified and maintained by a developer, so that small teams can pay more attention to their own work results and reflect their value without cooperation;

  • Microservices allow the use and integration of the latest technologies;

  • Microservices are just the code of business logic and will not be mixed with HTML, CSS or other interfaces;

  • Each microservice has its own storage capacity. It can have its own database or a unified database;

shortcoming

  • Developers need to deal with the complexity of distributed systems;
  • Multi service operation and maintenance is difficult. With the increase of services, the pressure of operation and maintenance is also increasing;
  • System deployment dependency;
  • Communication cost between services;
  • Data consistency;
  • System integration test problems;
  • Performance and monitoring issues;

1.4 microservice technology stack

Microservice Technology EntryLanding technology
Service developmentSpringBoot, Spring, Spring MVC, etc
Service configuration and managementArchaius of Netfix, Diamond of Ali, etc
Service registration and discoveryEureka, Consul, Zookeeper, etc
Service callRest,PRC,gRPC
Service fuseHystrix, Envoy, etc
load balancing Ribbon, Nginx, etc
Service interface call (simplified tool for client to call service)Fegin et al
Message queueKafka, RabbitMQ, ActiveMQ, etc
Service configuration center managementSpringCloudConfig, Chef, etc
Gateway service (API routing)Zuul et al
Service monitoringZabbix, Nagios, Metrics, specifier, etc
Full link trackingZipkin, Brave, Dapper, etc
Data flow operation development packageSpring cloud stream (encapsulating sending and receiving messages with Redis, Rabbit, Kafka, etc.)
Time message stackSpringCloud Bus
Service deploymentDocker, OpenStack, Kubernetes, etc

1.5 why choose spring cloud as the micro service architecture

Selection basis

  • Overall solution and framework maturity
  • Community heat
  • Maintainability
  • learning curve

Comparison of micro Service Frameworks

Function point / service frameworkNetflix/SpringCloudDubbo/DubboX
Functional positioningComplete microservice frameworkService Framework
Support RestYes, Ribbon supports a variety of pluggable serial number choicesno
Support RPCnoyes
Support multiple languagesYes (Rest form)no
load balancing Yes (server zuul + client Ribbon), zuul service, dynamic routing, cloud load balancing, Eureka (for middle tier servers)Yes (client)
Configure servicesNetfix Archaius, Spring Cloud Config Server, centralized configurationno
Service call chain monitoringYes (zuul). Zuul provides edge services and API gatewaysno
High availability / fault toleranceYes (server side Hystrix + client Ribbon)Yes (client)
Typical application casesNetflix

2 SpringCloud

2.1 spring cloud overview

SpringCloud, based on SpringBoot, provides a set of microservice solutions, including service registration and discovery, configuration center, full link monitoring, service gateway, load balancing, fuse and other components. In addition to the highly abstract encapsulation of open-source components based on NetFlix, there are also some selection neutral open-source components.

Spring cloud provides developers with some tools to quickly build distributed systems, such as configuration management, service discovery, circuit breaker, intelligent routing, micro agent, control bus, one-time token, global lock, decision election, distributed session and cluster state. With spring cloud, developers can quickly build and implement these services and applications. They work well in any distributed environment, including developers' own laptops, bare metal data centers and managed platforms such as cloud foundry.

SpringBoot does not make wheels repeatedly. It just combines the relatively mature service frameworks developed by various companies and can withstand the actual postgraduate entrance examination. It is repackaged through the SpringBoot style, shielding the complex configuration and implementation principles. Finally, it leaves a set of simple, easy to understand, easy to deploy and easy to maintain distributed system development kit for developers

SpringCloud is a one-stop solution under the distributed microservice architecture. It is a collection of landing technologies of various microservice architectures, commonly known as microservices.

2.2 relationship between springcloud and SpringBoot

In general, SpringBoot is used to develop microservices, while spring cloud is used to coordinate various microservices.

  • SpringBoot focuses on developing individual micro services quickly and conveniently;
  • SpringCloud is a microservice coordination and management framework that focuses on the overall situation. It integrates and manages individual microservices developed by SpringBoot, and provides integrated services between microservices: configuration management, service discovery, circuit breaker, routing, proxy, event stack, global lock, decision-making campaign, distributed session and so on;
  • SpringBoot can be used independently of SpringCloud to develop projects, but SpringCloud cannot be separated from SpringBoot, which belongs to dependency;
  • SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework;

2.3 Dubbo and SpringCloud technology selection

2.3.1 distributed + service governance Dubbo

The current mature Internet architecture, application service splitting + message middleware

2.3.2 comparison between Dubbo and spring cloud

DubboSpringCloud
Service registryZookeeperSpring Cloud Netfilx Eureka
Service invocation modeRPCREST API
Service monitoringDubbo-monitorSpring Boot Admin
Circuit breakerimperfectSpring Cloud Netfilx Hystrix
Service gatewaynothingSpring Cloud Netfilx Zuul
Distributed configurationnothingSpring Cloud Config
Service trackingnothingSpring Cloud Sleuth
Message stacknothingSpring Cloud Bus
data streamnothingSpring Cloud Stream
Batch tasknothingSpring Cloud Task

The biggest difference: Spring Cloud abandons Dubbo's RPC communication and adopts HTTP based REST

Strictly speaking, these two methods have their own advantages and disadvantages. Although to some extent, the latter sacrifices the performance of service invocation, it also avoids the problems caused by the above-mentioned native RPC. Moreover, REST is more flexible than RPC. The dependence of service providers and callers only depends on one contract, and there is no strong dependence at the code level. This advantage is more appropriate in the current microservice environment that emphasizes rapid evolution.

Similar to the difference between brand machine and assembly machine

**Summary: * * the two solve different problem domains: Dubbo is positioned as an RPC framework, while the goal of spring cloud is a one-stop solution under the microservice architecture

2.4 what can spring cloud do?

  • Distributed / versioned configuration

  • Service registration and discovery

  • Routing

  • Service to service calls

  • Load balancing configuration

  • Circuit Breakers

  • Distributed messaging

  • ...

3. Establishment of spring cloud rest learning environment

3.1 architecture of Maven subcontracting module

  • A Project with multiple sub modules

  • The SpringCloud parent Project is equipped with three sub modules for the first time

    • Spring cloud API: encapsulated overall entity / interface / public configuration, etc
    • springcloud-provider-dept-8001: service provider of micro service landing
    • springcloud-consumer-dept-80: client usage of microservice invocation

3.2 springcloud parent Project

  • Create a new parent project springcloud. Note that package is in pom mode.

  • The role of the parent project. It mainly defines the POM file and puts forward the common jar packages of subsequent sub modules, which is similar to an abstract parent class.

  • pom. The XML is shown in the figure below.

    <?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">
        <modelVersion>4.0.0</modelVersion>
        <groupId>cn.hubery</groupId>
        <artifactId>springcloud</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>pom</packaging>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <junit.version>4.12</junit.version>
            <log4j.version>1.2.17</log4j.version>
            <lombok.version>1.16.18</lombok.version>
        </properties>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Dalston.SR1</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-dependencies</artifactId>
                    <version>1.5.9.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.47</version>
                </dependency>
                <dependency>
                    <groupId>com.alibaba</groupId>
                    <artifactId>druid</artifactId>
                    <version>1.1.5</version>
                </dependency>
                <dependency>
                    <groupId>org.mybatis.spring.boot</groupId>
                    <artifactId>mybatis-spring-boot-starter</artifactId>
                    <version>1.3.0</version>
                </dependency>
                <dependency>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-core</artifactId>
                    <version>1.2.3</version>
                </dependency>
                <dependency>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                    <version>${junit.version}</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                    <version>${log4j.version}</version>
                </dependency>
            </dependencies>
        </dependencyManagement>
    </project>
    

3.3 springcloud API common sub Module

  • Create a sub module spring cloud API. After creation, it is found that the pom file of the parent project has more module attribute.

  • Modify POM of api module The XML file is as follows:

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-api</artifactId>
        <packaging>jar</packaging>
    
            <dependencies>
                <dependency>
                    <groupId>org.projectlombok</groupId>
                    <artifactId>lombok</artifactId>
                </dependency>
            </dependencies>
    </project>
    
  • Create a new Department Entity and use it with lombok.

  • After mvn clean install, it is referenced to other modules to achieve general purpose. That is, if you need to use department entities, you don't need to define one for each project. You can directly reference this module.

3.4 springcloud-provider-dept-8001 Department micro service provider Module

  • Create a new springcloud-provider-dept-8001. After creation, it is found that the pom file of the parent project has more module attribute.

  • Modify module of provider.pom The XML file is as follows:

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-provider-dept-8001</artifactId>
        <packaging>jar</packaging>
        <dependencies>
            <dependency>
                <groupId>cn.hubery</groupId>
                <artifactId>springcloud-api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jetty</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-test</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
    
        </dependencies>
    
    </project>
    
  • Write application yml

    server:
      port: 8001
    mybatis:
      config-location: classpath:mybatis/mybatisConfig.xml        # Path of mybatis configuration file
      type-aliases-package: cn.hubery.springcloud.entities       # Package of all Entity alias classes
      mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper mapping file
    spring:
      application:
        name: springcloud-dept #Name of exposed microservices
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource            # Current data source operation type
        driver-class-name: org.gjt.mm.mysql.Driver              # mysql driver package
        url: jdbc:mysql://localhost:3306/db01? & useencoding # SSL database name = true # code = false
        username: root
        password: root
        dbcp2:
          min-idle: 5                                           # Minimum number of maintained connections in the database connection pool
          initial-size: 5                                       # Number of initialized connections
          max-total: 5                                          # maximum connection
          max-wait-millis: 200                                  # Maximum timeout waiting for connection acquisition
    
  • Create a new mybatis folder under the resources directory, and then create a new mybatisconfig XML file (the current function is only to open the L2 cache).

  • Create database tables.

  • DeptDao Department interface.

  • Create a mapper folder under resources/mybatis directory and then create deptmapper xml.

  • DeptService department service interface.

  • DeptServiceImpl department service interface implementation class.

  • DeptController Department micro service provider REST.

  • DeptProvider8001_App main startup class.

3.5 springcloud-consumer-dept-80

  • Create a new springcloud-consumer-dept-80 Department micro service consumer Module.

  • Modify pom file

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-consumer-dept-80</artifactId>
        <packaging>jar</packaging>
    
        <dependencies>
            <dependency>
                <groupId>cn.hubery</groupId>
                <artifactId>springcloud-api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    
  • yml modify the port number to 80.

  • Preparation of ConfigBean (similar to the injection Bean written in applicationContext.xml in spring). Because you want to inject the existing RestTemplate.

    • RestTemplate provides a variety of convenient methods to access remote Http services. It is a simple and convenient template class to access restful services. It is the client template tool set provided by Spring to access Rest services

    • Call the service provided by the remote provider through RestTemplate.

      @RestController
      public class DeptControllerConsumer {
          @Autowired
          private RestTemplate restTemplate;
      
          private static final String REST_URL_PREFIX= "http://localhost:8001";
          /*
          Using restTemplate to access restful interface is very simple and rude.
          (url, requestMap, ResponseBean.class)These three parameters represent the REST request address, request parameters and the object type converted by HTTP response conversion.
           */
          @RequestMapping(value = "/consumer/dept/add")
          public boolean add( Dept dept) {
              return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
          }
      
          @RequestMapping(value = "/consumer/dept/get/{id}")
          public Dept get(@PathVariable("id") Long id) {
              return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
          }
      
          @RequestMapping(value = "/consumer/dept/list")
          public List<Dept> list() {
              return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
          }
      }
      
  • DeptConsumer80_App main startup class

4 Eureka service registry

4.1 General

Netflix followed the AP principle when designing Eureka.

CAP principle, also known as CAP theorem, refers to that in a distributed system, Consistency, Availability and Partition tolerance cannot have both.

Eureka is a sub module of Netflix and one of the core modules. Eureka is a REST based service, which is used to locate services to realize cloud middle tier service discovery and failover. Service registration and discovery is very important for micro service architecture. With service discovery and registration, you can access the service only by using the service identifier without modifying the configuration file of service invocation. The function is similar to dubbo's registry, such as Zookeeper.

4.2 Eureka principle

4.2.1 basic structure

  • Spring Cloud encapsulates the Eureka module developed by Netflix to realize service registration and discovery (please compare Zookeeper).

  • Eureka adopts the C-S design architecture. Eureka Server, as a server with service registration function, is the service registration center.

  • Other microservices in the system use Eureka's client to connect to Eureka Server and maintain heartbeat connection. In this way, the maintenance personnel of the system can monitor whether each micro service in the system is running normally through Eureka Server. Some other modules of spring cloud (such as Zuul) can discover other micro services in the system through Eureka Server and execute relevant logic.

Eureka:

Dubbo:

Eureka consists of two components: Eureka Server and Eureka Client

Eureka Server provides service registration services

After each node is started, it will be registered in EurekaServer, so that the service registry in EurekaServer will store the information of all available service nodes, and the information of service nodes can be seen intuitively in the interface.

Eureka Client is a Java client, which is used to simplify the interaction of Eureka Server. The client also has a built-in load balancer using round robin load algorithm. After the application starts, a heartbeat will be sent to Eureka Server (the default cycle is 30 seconds). If Eureka Server does not receive the heartbeat of a node in multiple heartbeat cycles, Eureka Server will remove the service node from the service registry (90 seconds by default)

4.2.2 three roles

  • Eureka Server: provides service registration and discovery
  • Service Provider: the service producer registers its own service in Eureka, so that the service consumer can find it
  • Service Consumer: the Service Consumer. Get the list of registered services from Eureka to find the consumer services

4.3 register Eureka and find

4.3.1 create Eureka and register the service

  • Create springcloud-eureka-7001 eureka service registry Module.

    • pom

      <?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>springcloud</artifactId>
              <groupId>cn.hubery</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>springcloud-eureka-7001</artifactId>
          <dependencies>
              <!--eureka Server-->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-eureka-server</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>springloaded</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-devtools</artifactId>
              </dependency>
          </dependencies>
      
      </project>
      
    • yml

      server:
        port: 7001
      eureka:
        instance:
          hostname: localhost #Instance name of eureka server
        client:
          register-with-eureka: false #false means that you do not register yourself with the registry.
          fetch-registry: false #false means that my client is the registration center. My responsibility is to maintain service instances and I don't need to retrieve services
          service-url:
            defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka / # set the address to interact with Eureka Server. Both query service and registration service need to rely on this address.
      
    • EurekaServer7001_App main startup class@ Enable eurekaserver / / mark this item as eurekaserver and accept other micro services to register.

  • Register provider

    • Modify the pom file of the provider and add the following

      <!--Check in Eureka Registration Center-->
      <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-eureka</artifactId>
      </dependency>
      
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-config</artifactId>
          
      </dependency>
      
    • Modify the yml file of the provider and add the following

      eureka:
        client: #The client is registered in the eureka server list
          service-url:
            defaultZone: http://localhost:7001/eureka/
      
    • DeptProvider8001_ Start the main class of ekaapp and add the main class of enableclient// Identify EurekaClient

  • Actor and the improvement of registered micro service information

    • Host name: service name modification
    • IP information prompt for access information
    • Microservice info content details

4.3.2 EureKa self-protection mechanism: living is better than dying

In a word, if a micro service is unavailable at a certain time, eureka will not clean it immediately, but will still save the information of the micro service!

By default, if EurekaServer does not receive the heartbeat of a micro service instance within a certain period of time, EurekaServer will log off the instance (90 seconds by default).

However, when the network partition fails, the micro service and EurekaServer cannot communicate normally, and the above behavior may become very dangerous - because the micro service itself is actually healthy, and the micro service should not be cancelled at this time. Eureka solves this problem through "self-protection mode"

When EurekaServer node loses too many clients in a short time (network partition failure may occur), the node will enter self-protection mode. Once in this mode, EurekaServer will protect the information in the service registry and will not delete the data in the service registry (that is, it will not log off any microservices). When the network fault recovers, the Eureka Server node will automatically exit the self-protection mode.

In self-protection mode, Eureka Server will protect the information in the service registry and will not log off any service instances. When the number of heartbeats it receives recovers above the threshold, the Eureka Server node will automatically exit the self-protection mode. Its design philosophy is to retain the wrong service registration information rather than blindly cancel any possible healthy service instances. In one sentence: it's better to live than to die

To sum up, self-protection mode is a security protection measure to deal with network abnormalities. Its architectural philosophy is that it would rather retain all micro services at the same time (both healthy and unhealthy micro services will be retained), rather than blindly cancel any healthy micro services. Using self-protection mode can make Eureka cluster more robust and stable.

In Spring Cloud, you can use Eureka server. Enable self preservation = false disables self-protection mode.

4.3.3 EureKa service discovery

  • For the micro service registered in eureka, the client can obtain the information of the service through service discovery.

  • Modify the DeptController of the springcloud-provider-dept-8001 project

4.4 EureKa cluster configuration

4.4.1 create two new EureKa services

  • Create two EureKa modules. springcloud-eureka-7002,springcloud-eureka-7003.
  • POM XML add dependency (same as springcloud-eureka-7001).
  • Main startup class (same as springcloud-eureka-7001).
  • application.yml configuration (same as spring cloud-eureka-7001).

4.4.2 cluster members are related to each other - modify mapping configuration

  • Modify the mapping configuration and add it to the hosts file (virtual three servers)

    • 127.0.0.1 eureka7001.com
    • 127.0.0.1 eureka7002.com
    • 127.0.0.1 eureka7003.com
  • Modify application Yam file

    • eureka.instance.hostname

    • Cluster Association, such as yml file of 7001

      server:
        port: 7001
      eureka:
        instance:
          hostname: eureka7001.com #Instance name of eureka server
        client:
          register-with-eureka: false #false means that you do not register yourself with the registry.
          fetch-registry: false #false means that my client is the registration center. My responsibility is to maintain service instances and I don't need to retrieve services
          service-url:
            #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka / # set the address to interact with Eureka Server. Both query service and registration service need to rely on this address.
            defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ #Association
      
  • Modify the service provider 8001 and register in the 1 / 2 / 3 Registration Center at the same time.

4.5 comparison between Eureka and Zookeeper

4.5.1 review CAP principles

RDBMS (MySQL\Oracle\sqlServer) ===> ACID

NoSQL (Redis\MongoDB) ===> CAP

4.5.2 what is acid?

A (Atomicity)

C (Consistency)

I (Isolation)

D (Durability)

4.5.1 what is a cap?

C (Consistency) strong consistency: whether all data backups in the distributed system have the same value at the same time. (equivalent to all nodes accessing the same latest data copy)

A (Availability): ensure that every request has a response regardless of success or failure.

P (Partition tolerance): the loss or failure of any information in the system will not affect the continuous operation of the system.

Three in two of CAP: CA, AP, CP

4.5.4 core of cap theory

A distributed system cannot meet the three requirements of consistency, availability and partition fault tolerance at the same time

According to the principle of CAP, NoSQL database is divided into three categories: meeting CA principle, meeting CP principle and meeting AP principle

CA: single point cluster. Systems that meet consistency and availability usually have poor scalability

CP: a system that meets consistency and partition fault tolerance. Generally, the performance is not particularly high

AP: a system that meets the requirements of availability and partition fault tolerance. Generally, it may have lower requirements for consistency

4.5.5 as a distributed service registry, where is Eureka better than Zookeeper?

The famous CAP theory points out that A distributed system cannot meet C (consistency), A (availability) and P (fault tolerance) at the same time. Because partition fault tolerance P must be guaranteed in the distributed system, we can only trade off between A and C.

Zookeeper ensures that CP - > systems that meet consistency and partition fault tolerance usually have low performance.

Eureka guarantees that AP - > systems that meet availability and partition fault tolerance may generally have lower requirements for consistency.

Zookeeper guarantees CP

When querying the service list from the registry, we can tolerate that the registry returns the registration information a few minutes ago, but we can't receive the service and directly down it. In other words, the service registration function requires higher availability than consistency. However, there will be such a situation in zookeeper. When the master node loses contact with other nodes due to network failure, the remaining nodes will conduct leader election again. The problem is that the election leader takes too long, 30-120s, and the whole zookeeper cluster is unavailable during the election, which leads to the paralysis of the registration service during the election. In the cloud deployment environment, the loss of the master node of the zookeeper cluster due to network problems is an event with a high probability. Although the service can be restored eventually, the long election time leads to the long-term unavailability of registration, which is intolerable.

Eureka guarantees AP

Eureka understands this, so it gives priority to ensuring availability in design. Eureka's nodes are equal. The failure of several nodes will not affect the work of normal nodes, and the remaining nodes can still provide registration and query services. When Eureka's client registers with an Eureka, if it finds that the connection fails, it will automatically switch to other nodes. As long as one Eureka is still there, the availability of the registration service can be maintained, but the information found may not be up-to-date. In addition, Eureka also has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, Eureka thinks that there is a network failure between the client and the registry. At this time, the following situations will occur:

  • Eureka is no longer removing services that should expire because they haven't received a heartbeat for a long time from the registration list.

  • Eureka can still accept the registration and query requests of new services, but it will not be synchronized to other nodes (that is, ensure that the current node is still available).

  • When the network is stable, the new registration information of the current instance will be synchronized to other nodes.

Therefore, Eureka can deal with the loss of contact of some nodes due to network failure without paralyzing the whole registration service like zookeeper.

5 Ribbon load balancing

5.1 overview of spring cloud ribbon

5.1.1 what is ribbon?

  • Spring Cloud Ribbon is a set of client-side load balancing tools based on Netflix Ribbon.

In short, ribbon is an open source project released by Netflix. Its main function is to provide software load balancing algorithms for clients and connect Netflix's middle tier services together. Ribbon client component provides a series of perfect configuration items, such as connection timeout, Retry, etc. To put it simply, list all the machines behind the Load Balancer (LB) in the configuration file. The ribbon will automatically help you connect these machines based on certain rules (such as simple polling, random connection, etc.). We can also easily use ribbon to implement custom load balancing algorithms.

5.1.2 what can ribbon do?

  • LB, load balance, is an application often used in microservices or distributed clusters.

  • Load balancing simply means that users' requests are evenly distributed to multiple services, so as to achieve the HA of the system.

  • Common load balancing include software Nginx, LVS, hardware F5, etc.

  • Accordingly, load balancing is provided to us in middleware, such as dubbo and spring cloud. The load balancing algorithm of spring cloud can be customized.

  • Simple classification of load balancing:

    • Centralized LB
      • That is, an independent LB facility (which can be hardware, such as F5, or software, such as nginx) is used between the service provider and the consumer. The facility is responsible for forwarding the access request to the service provider through some policy!
    • Program LB
      • Integrate LB logic into the consumer. The consumer knows which addresses are available from the service registry, and then selects a suitable server from these addresses.

      • Ribbon belongs to in-process LB, which is just a class library integrated into the consumer process. The consumer obtains the address of the service provider through it!

5.2 preliminary configuration of integrated Ribbon

  • Modify pom. springcloud-consumer-dept-80 to pom Add Ribbon and Eureka dependencies to XML
<!--add to Ribbon-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
  • Modify application YML adds the service registration address of eureka

    eureka:
      client:
        register-with-eureka: false # Do not register yourself with Eureka
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    
  • Add a new annotation to ConfigBean @ LoadBalanced. Add the configuration of Ribbon when you get Rest.

  • Main startup class deptconsumer80_ Add @ EnableEurekaClient to app.

  • Modify DeptController_Consumer client access class.

    private static final String REST_URL_PREFIX="http://SPRINGCLOUD-DEPT/";
    //private static final String REST_URL_PREFIX= "http://localhost:8001";
    //After the integration of Ribbon and Eureka, the Consumer can directly call the service without caring about the address and port number. Above comparison
    

5.3 Ribbon load balancing

5.3.1 architecture diagram

5.3.2 adding service provider clusters

  • Create two copies of cloud provider-80003 and cloud provider-80003 respectively.

  • Create a new 8002 / 8003 database, and connect their own microservices to their own databases. (the actual operation is not like this. The database master-slave replication mode is just a simple demonstration of the cluster)

  • Modify the YML of 8002 / 8003 (modify the port number, modify the database, modify the eureka.instance.instance-id host name)

  • Unified service instance name exposed to the outside world. spring.application.name. Because it is a different host (server) for the same service, you should use the same server instance name.

  • By default, the polling algorithm is used for load balancing. That is, the load is balanced in an orderly manner such as 1-2-3-1.

5.3.3 Ribbon core component IRule

IRule: select a service to be accessed from the service list according to a specific algorithm

1. Use the defined centralized load balancing algorithm:

Configure beans in ConfigBean. For example:

@Bean
public IRule myRule(){
    return new RandomRule();//The purpose is to use the re selected random algorithm
}
  • Roundrobin rule: polling
  • RandomRule: random
  • Availability filtering rule: first filter out the services in the state of circuit breaker tripping due to multiple access faults and the services with concurrent connections exceeding the threshold, and then access the remaining service list according to the polling policy
  • WeightedResponseTimeRule: calculate the weight of all services according to the average response time. The faster the response time, the greater the service weight, and the higher the probability of being selected. If the statistical information is insufficient at the beginning of startup, the roundrobin rule policy will be used. When the statistical information is sufficient, it will switch to WeightedResponseTimeRule.
  • RetryRule: first obtain the service according to the roundrobin rule policy. If the service acquisition fails, it will retry within the specified time to obtain the available service.
  • Best available rule: it will first filter out the services in the circuit breaker tripping state due to multiple access faults, and then select a service with the least concurrency.
  • ZoneAvoidanceRule: the default rule, which determines the performance of the region where the server is located and the availability of the server, and selects the server.

2. Use custom load balancing algorithm

  • Add @ RibbonClient to the main startup class

    • When starting the micro service, we can load our custom Ribbon configuration class to make the configuration take effect.
    • For example: @ RibbonClient(name = "MICROSERVICECLOUD-DEPT", configuration=MySelfRule.class)
  • Create a custom MySelfRule class

    • The official document clearly gives a warning:

      • This custom configuration class cannot be placed under the current package and sub package scanned by @ ComponentScan, otherwise our custom configuration class will be shared by all Ribbon clients, that is, we can't achieve the purpose of special customization. (it cannot be the same package as the main startup)
      //Create a package at the same level as the main startup class package, and create MySelfRule under this package
      @Configuration
      public class MySelfRule {
          @Bean
          public IRule myRule() {
              return new RandomRule();//The Ribbon defaults to polling, and I customize it as random
          }
      }
      
  • At this time, the load balancing algorithm corresponding to the existing RandomRule class is used. How to implement a custom one?

  • The polling strategy is still used, but with new requirements, each server is required to be called 5 times. That is, once for each machine before, now it is 5 times for each machine

    • The reference source code is modified to roundrobin rule in the requirement_ New. java

      public class RoundRobinRule_New extends AbstractLoadBalancerRule {
          private int total = 0;    //The total number of calls. At present, each machine is required to be called 5 times. When total==5, it can go down from the service list
          private int currentIndex = 0;//Machine number of the current service
      
          /**
           * If each service is accessed 5 times, the next service will be replaced (a total of 3 services)
           * <p>
           * total=0,Default = 0. If = 5, it points to the next service node
           * index=0,Default = 0, if total=5,index+1
           */
      
          public Server choose(ILoadBalancer lb, Object key) {
              if (lb == null) {
                  return null;
              }
              Server server = null;
              while (server == null) {
                  if (Thread.interrupted()) {
                      return null;
                  }
                  List<Server> upList = lb.getReachableServers();//Access to currently alive services
                  List<Server> allList = lb.getAllServers();//Get all services
                  int serverCount = allList.size();
                  if (serverCount == 0) {
                      /*
                       * No servers. End regardless of pass, because subsequent passes
                       * only get more restrictive.
                       */
                      return null;
                  }
      //            int index = rand.nextInt(serverCount);
      //            server = upList.get(index);
                  if (total < 5) {//Less than 5, continue to call the machine currently providing services
                      server = upList.get(currentIndex);//Obtain the specified service from the living service for operation
                      total++;
                  } else {//Greater than 5, call the next machine providing services
                      total = 0;
                      currentIndex++;
                      if (currentIndex >= upList.size()) {
                          currentIndex = 0;
                      }
                      server = upList.get(currentIndex);//Obtain the specified service from the living service for operation
                  }
                  if (server == null) {
                      /*
                       * The only time this should happen is if the server list were
                       * somehow trimmed. This is a transient condition. Retry after
                       * yielding.
                       */
                      Thread.yield();
                      continue;
                  }
                  if (server.isAlive()) {
                      return (server);
                  }
      // Shouldn't actually happen.. but must be transient or a bug.
                  server = null;
                  Thread.yield();
              }
              return server;
          }
      
          @Override
          public Server choose(Object key) {
              return choose(getLoadBalancer(), key);
          }
      
      
          @Override
          public void initWithNiwsConfig(IClientConfig iClientConfig) {
      
          }
      }
      
    • Change the object of myRule() method new in MySelfRule to a custom class

6 Feign load balancing

6.1 Feign introduction

Feign is a declarative Web service client, which makes it very easy to write a Web service client. Similar to the controller calling a service, you only need to create an interface and add comments on it.

Feign, mainly the community version, is used to interface oriented programming. This is the norm for many developers.

There are two methods to call microservice access:

  • Get the calling address from the microservice name
  • Interface + annotation to obtain the calling service

6.1.1 what can feign do

  • Feign aims to make it easier to write Java Http clients.

  • When Ribbon+RestTemplate is used earlier, a set of template calling methods is formed by encapsulating http requests with RestTemplate. However, in the actual development, because there may be more than one invocation of service dependencies, and often an interface will be invoked in multiple places, some client classes are usually encapsulated for each micro service to wrap the invocation of these dependent services. Therefore, Feign made further encapsulation on this basis to help us define and implement the definition of dependent service interfaces. Under the implementation of Feign, we only need to create an interface and configure it in the way of annotation (previously, the Dao interface was marked with Mapper annotation, but now it is a micro service interface marked with Feign annotation), so as to complete the interface binding to the service provider, which simplifies the development of automatically encapsulating the service call client when using the Spring cloud Ribbon.

6.1.2 Feign integrates Ribbon

  • The Ribbon is used to maintain the service list information of microservicecloud dept, and the load balancing of the client is realized through polling. Unlike Ribbon, feign only needs to define the service binding interface, and implements the service invocation gracefully and simply in a declarative way.

6.2 use of feign

  • Refer to springcloud-consumer-dept-80 to create a springcloud-consumer-dept-feign. Modify the name of the main startup class.

  • Modify the POM of fegin module xml. Add fegin support.

  • Modify the spring cloud API.

    • Public interface into api

    • Add fegin support to pom of api.

    • Create a new DeptClientService interface and add the annotation @ FeignClient.

      @FeignClient(value = "SPRINGCLOUD-DEPT")
      public interface DeptClientService
      {
      @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET)
      public Dept get(@PathVariable("id") longid);
      
      
      @RequestMapping(value = "/dept/list",method = RequestMethod.GET)
      public List list();
      
      
      @RequestMapping(value = "/dept/add",method = RequestMethod.POST)
      publicboolean add(Dept dept);
      }
      
  • Modify the controller of fegin. Interface oriented style. Feign call method is more in line with our previous programming habit of calling the Service layer by the controller layer when we were working on SSM or sprnboot projects!

    @RestController
    public class DeptControllerConsumer {
    
        @Autowired
        private DeptClientService deptClientService=null;
    
        /**
         * Add department information to the consumer
         * @param dept Department information
         * @return Success flag
         */
        @RequestMapping("/consumer/dept/add")
        public boolean add(Dept dept) {
            return deptClientService.add(dept);
        }
    
        /**
         * The consumer queries the Department information according to the id
         * @param id Department id
         * @return department
         */
        @RequestMapping("/consumer/dept/get/{id}")
        public Dept get(@PathVariable("id") Long id) {
            return deptClientService.get(id);
        }
    
        /**
         * Consumer query department information list
         * @return All departments
         */
        @RequestMapping("/consumer/dept/list")
        public List list() {
            return deptClientService.list();
        }
    }
    
  • Main startup class modification annotation

    @SpringBootApplication(scanBasePackages = "cn.hubery.springcloud")
    @EnableEurekaClient
    @EnableFeignClients(basePackages= {"cn.hubery.springcloud"})
    

Feign has its own load balancing configuration item.

6.3 summary and selection

Summary:

Feign calls the Rest service through the method of the interface (previously Ribbon+RestTemplate),

The request is sent to Eureka server( http://SPRINGLOUD-DEPT/dept/list ),

Find the service interface directly through Feign. Because the Ribbon technology is integrated in the service call, it also supports the role of load balancing.

How Feign and Ribbon choose:

  • It depends on personal habits. If you like REST style, use Ribbon; If you like the community version of the interface oriented style, use Feign

  • Feign essentially implements Ribbon, but the latter is in the calling mode, in order to meet the interface calling habits of some developers.

7 Hystrix services

7.1 general

7.1.1 problems faced by distributed system

Applications in complex distributed architecture have dozens of dependencies, and each dependency will inevitably fail at some time.

Service avalanche

When calling between multiple microservices, suppose that microservice A calls microservice B and microservice C, and microservice B and microservice C call other microservices, which is the so-called "fan out".

If the call response time of A microservice on the fan out link is too long or unavailable, the call to microservice A will occupy more and more system resources, resulting in system crash, the so-called "avalanche effect"

For high traffic applications, a single back-end dependency may cause all resources on all servers to saturate in a few seconds. Worse than failure, these applications may also lead to increased delays between services, tight backup queues, threads and other system resources, resulting in more cascading failures of the whole system. These indicate the need to isolate and manage failures and delays so that the failure of a single dependency cannot cancel the entire application or system (purpose).

**Note: * * in general, there are three main solutions for the protection of service dependency:

(1) Fusing mode: this mode mainly refers to the fusing of the reference circuit. If the voltage of a line is too high, the fuse will blow to prevent fire. In our system, if a target service is called slowly or has a large number of timeouts, the call of the service will be fused. For subsequent call requests, we will not continue to call the target service, return directly and quickly release resources. If the target service improves, resume the call.

(2) Isolation mode: this mode is like dividing the system request into small islands according to type. When a small island is burned out, it will not affect other small islands. For example, thread pools can be used to isolate resources for different types of requests. Each type of request does not affect each other. If the thread resources of one type of request are exhausted, the subsequent requests of this type will be returned directly without calling subsequent resources. There are many usage scenarios for this mode, such as splitting a service, deploying important services with a separate server, or the multi center recently promoted by the company.

(3) Current limiting mode: the above fusing mode and isolation mode belong to the fault-tolerant processing mechanism after error, and the current limiting mode can be called the prevention mode. The current limiting mode is mainly to set the highest QPS threshold for each type of request in advance. If it is higher than the set threshold, the request will be returned directly without calling subsequent resources. This model can not solve the problem of service dependency, but can only solve the problem of overall resource allocation of the system, because requests without flow restriction may still cause avalanche effect.

7.1.2 what is hystrix

Hystrix is an open source library for dealing with delay and fault tolerance of distributed systems. In distributed systems, many dependencies inevitably fail to call, such as timeout, exception, etc.

Hystrix can ensure that when a dependency fails, it will not lead to overall service failure, avoid cascading failures, and improve the elasticity of distributed systems.

"Circuit breaker" itself is a kind of switching device. When a service unit fails, it returns an expected and treatable alternative response (FallBack) to the caller through the fault monitoring of the circuit breaker (similar to a blown fuse), rather than waiting for a long time or throwing an exception that the caller cannot handle, This ensures that the thread of the service caller will not be occupied unnecessarily for a long time, so as to avoid the spread and even avalanche of faults in the distributed system.

7.1.4 what can hystrix do

  • Service fuse
  • service degradation
  • Service current limiting
  • Near real-time monitoring

7.2 service fuse

7.2.1 concept

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

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 the fuse mechanism is @ HystrixCommand.

  • Solve the following problems
    • When the dependent object is unstable, it can achieve the purpose of rapid failure;
    • After a fast failure, it can dynamically test whether the dependent object is restored according to a certain algorithm.

7.2.2 use of service fuse

  • Refer to the service provider and create the springcloud provider dept hystrix 8001 sub module

  • Add spring cloud starter hystrix support

  • Modify DeptController -------- once calling the service method fails and an error message is thrown, it will automatically call the specified method in the fallbackMethod calling class marked by @ HystrixCommand

    //Use RestController when springboot
    @RestController
    public class DeptController {
    
        @Autowired
        private DeptService deptService;
    
        /**
         * Query department information according to id
         * If an exception occurs in the id query, go to processHystrix_Get this alternative code
         */
        @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET)
        @HystrixCommand(fallbackMethod = "processHystrix_Get")
        public Dept get(@PathVariable("id") Long id)
        {
            Dept dept =  this.deptService.get(id);
            if(null == dept)
            {
                throw new RuntimeException("Should ID: "+id+"No corresponding information");
            }
            return dept;
        }
    
        /**
         * Query alternatives according to id (fuse)
         */
        public Dept processHystrix_Get(@PathVariable("id") Long id)
        {
            return new Dept().setDeptno(id)
                .setDname("Should ID: "+id+"No corresponding information,null--@HystrixCommand")
                .setDb_source("no this database in MySQL");
        }
    
        @RequestMapping(value="/dept/add",method= RequestMethod.POST)
        public boolean add(@RequestBody Dept dept)
        {
            return deptService.add(dept);
        }
    
        @RequestMapping(value="/dept/list",method=RequestMethod.GET)
        public List<Dept> list()
        {
            return deptService.list();
        }
    }
    
  • Modify the main startup class DeptProvider8001_Hystrix_App and add a new annotation @ enablercircuitbreaker. Support for hystrixR circuit breaker mechanism

  • The function of the above program is to access the nonexistent id and jump to another method.

7.3 service degradation

The service degradation process is implemented on the client side and has nothing to do with the server side

7.3.1 concept

It refers to that when the pressure of the server increases sharply, some services and pages are not handled strategically or handled in a simple way according to the actual business conditions and traffic, so as to release the server resources to ensure the normal or efficient operation of the core business. To put it bluntly, it is to give system resources to services with high priority as much as possible.

Resources are limited and requests are unlimited. If the service is not degraded during the peak period of concurrency, on the one hand, it will certainly affect the performance of the overall service. If it is serious, it may lead to downtime and unavailability of some important services. Therefore, in the peak period, in order to ensure the availability of core function services, some services must be degraded. For example, when the double 11 event is held, all services unrelated to the transaction are downgraded, such as viewing ant deep forest, viewing historical orders, etc.

7.3.2 main usage scenarios of service degradation

When the overall load of the whole microservice architecture exceeds the preset upper threshold or the upcoming traffic is expected to exceed the preset threshold, some unimportant or non urgent services or tasks can be delayed or suspended in order to ensure the normal operation of important or basic services.

For example, you can add points to the service cache according to the method of service execution delay; Or close the service within the granularity, such as the recommendation of relevant articles.

7.3.3 problems to be considered in service degradation

  • Which services are core services and which are non core services
  • Which services can support degradation, which services cannot support degradation, what is the degradation strategy
  • In addition to service degradation, is there a more complex business release scenario and what is the strategy

7.3.4 automatic degradation classification

  • Timeout degradation: it mainly configures the timeout time and timeout retry times and mechanism, and uses asynchronous mechanism to detect the reply

  • Degradation of failure times: it mainly refers to some unstable APIs. When the number of failed calls reaches a certain threshold, it will be degraded automatically. Similarly, asynchronous mechanism should be used to detect the reply

  • Failure degradation: for example, if the remote service to be called hangs (network failure, DNS failure, http service returns an error status code, rpc service throws an exception), it can be directly degraded. The processing schemes after degradation include: default value (for example, if the inventory service is suspended, return to the default stock), bottom data (for example, if the advertisement is suspended, return some static pages prepared in advance), cache (some cache data temporarily stored before)

  • Current limit degradation: when second killing or rush buying some restricted goods, the system may crash due to too much traffic. At this time, the current limit will be used to limit the traffic. When the current limit threshold is reached, the subsequent requests will be degraded; The processing scheme after degradation can be: queue page (divert the user to the queue page and try again later), no goods (directly inform the user that there is no goods), error page (if the activity is too hot, try again later).

7.3.5 use of service degradation

  • Modify api project. Create a new class DeptClientServiceFallbackFactory that implements the FallbackFactory interface according to the existing DeptClientService interface.

    Pay special attention to the problem of registering spring components in api projects!

    @Component//Don't forget to add, don't forget to add
    public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>{
        @Override
        public DeptClientService create(Throwable throwable)
        {
            return new DeptClientService() {
                @Override
                public Dept get(long id)
                        {
                                return new Dept().setDeptno(id)
                                .setDname("Should ID: "+id+"No corresponding information,Consumer Degradation information provided by the client,Service now Provider Closed")
                                .setDb_source("no this database in MySQL");
                }
                @Override
                public List list()
                {
                    return null;
                }
                @Override
                public boolean add(Dept dept)
                {
                    return false;
                }
            };
        }
    }
    
  • Continue to modify the api project. The DeptClientService interface adds the fallbackfactory attribute value in the annotation * * @ FeignClient * *. After that, reinstall the api project. fallbackFactory=DeptClientServiceFallbackFactory.class

  • Modify the YML file of the springcloud consumer dept feign project and set feign hystrix. The enabled property value is true. Open hystrix

  • Note the notes of the spring cloud consumer dept feign project

    @SpringBootApplication(scanBasePackages = {"cn.hubery.springcloud","cn.hubery.springcloud.service"})
    //@The spring bootapplication annotation will scan this directory and the service directory of the api project and register the bean s in it
    @EnableEurekaClient
    @EnableFeignClients(basePackages= {"cn.hubery.springcloud"})
    //@ComponentScan() when @ SpringBootApplication takes effect, if this annotation is used, the function of scanning spring components in this directory by default will be lost, so the scanning must be displayed.
    

7.3.6 difference between service fusing and degradation

  • Service fusing - > server: a service timeout or abnormality causes fusing ~, which is similar to a fuse (Self Fusing)
  • Service degradation - > client: considering the overall website request load, when a service is blown or closed, the service will no longer be called. At this time, on the client, we can prepare a FallBackFactory and return a default value (default value). It will lead to the decline of the overall service, but at least it can be used, which is better than hanging up directly.
  • The triggering reasons are different. Service fusing is generally caused by a service (downstream service) failure, and service degradation is generally considered from the overall load;
  • The levels of management objectives are different. Fusing is actually a framework level process, and each micro service needs to be (without hierarchy), while degradation generally needs to have hierarchy for the business (for example, degradation generally starts from the most peripheral services)
  • The implementation method is different. Service degradation is code intrusive (completed by the controller and / or automatic degradation), and fusing is generally called self fusing.

Three concepts ---- fusing, degradation and current limiting:

Flow restriction: limit concurrent request access. If the threshold is exceeded, it will be rejected;

Degradation: services are prioritized, sacrificing non core services (unavailable) to ensure the stability of core services; Considering the overall load;

Fusing: the dependent downstream service failure triggers fusing to avoid causing the system to crash; The system performs and restores automatically.

7.4 use of dashboard flow monitoring

Hytrix provides a quasi real-time call monitoring (hytrix dashboard). Hytrix will continuously record the execution information of all requests initiated through hytrix and display it to users in the form of statistical reports and graphics, including how many requests are executed, how many are successful, how many are failed, etc. Netflix monitors the above indicators through the Hystrix metrics event stream project. Spring Cloud also provides the integration of the Hystrix Dashboard to transform the monitoring content into a visual interface.

  • New springcloud consumer hystrix dashboard project

  • Add pom dependency

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    </dependency>
    
  • Add yml port number

  • Create the main startup class and add annotations,

    @SpringBootApplication
    @EnableHystrixDashboard
    
  • Import monitoring dependency packages in various micro service providers

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  • http://localhost:9001/hystrix

    • Effect drawing after filling in the monitoring address:

8 zuul routing gateway

8.1 general

Zuul includes two main functions of request routing and filtering:

The routing function is responsible for forwarding external requests to specific micro service instances, which is the basis for realizing the unified entrance of external access, while the filter function is responsible for intervening in the processing process of requests, which is the basis for realizing the functions of request verification, service aggregation and so on

Zuul and Eureka integrate, register zuul as an application under Eureka service governance, and obtain messages of other micro services from Eureka, that is, access to micro services in the future is obtained through zuul jump.

Note: Zuul service will eventually register with Eureka

It provides three functions: agent + routing + filtering

Zuul is used for routing and filtering.

8.2 configuration and use of zuul

  • New Module springcloud-zuul-gateway-9527

  • Add pom dependency

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-zuul-gateway-9527</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-zuul</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-hystrix</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>
            <dependency>
                <groupId>cn.hubery</groupId>
                <artifactId>springcloud-api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jetty</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-test</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
    
        </dependencies>
    
    
    </project>
    
  • Add hosts mapping 127.0.0.1 myzuul com

  • Add @ EnableZuulProxy annotation to the main startup class

  • yml document preparation

    server:
      port: 9527
    spring:
      application:
        name: springcloud-zuul-gateway
    eureka:
      client:
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
      instance:
        instance-id: gateway-9527.com
        prefer-ip-address: true
    
    
    zuul:
      prefix: /hubery   #prefix
      ignored-services: springcloud-dept  #Ignore this route access
      routes:
        mydept.serviceId: springcloud-dept   #Original real service name routing
        mydept.path: /mydept/**        #New route name
    
    
    
    info:
      app.name: huebry-springcloud
      company.name: www.huebrytu.cn
      build.artifactId: $project.artifactId$
      build.version: $project.version$
    

9 Spring Cloud Config distributed configuration

9.1 general

9.1.1 - configuration problems faced by distributed systems

Microservice means to split the business in a single application into one sub service. The granularity of each service is relatively small, so there will be a large number of services in the system. Because each service needs the necessary configuration information to run, a centralized and dynamic configuration management facility is essential. Spring cloud provides ConfigServer to solve this problem. Each microservice brings an application YML, the management of hundreds of configuration files becomes very troublesome

9.1.2 what is springcloud config?

SpringCloud Config provides centralized external configuration support for microservices in the microservice architecture, and the configuration server provides a centralized external configuration for all environments of different microservice applications.

SpringCloud Config is divided into two parts: server and client.

  • The server is also called distributed configuration center. It is an independent micro service application, which is used to connect to the configuration server and provide access interfaces for the client to obtain configuration information, encryption / decryption information and so on.

  • The client manages application resources and business-related configuration content through the specified configuration center, and obtains and loads configuration information from the configuration center at startup. By default, the configuration server uses git to store configuration information, which is helpful for version management of environment configuration, and the configuration content can be easily managed and accessed through git client tools.

9.1.3 role of springcloud config

  • Centralized management profile
  • Different environments, different configurations, dynamic configuration updates, deployment by environment, such as / dev /test /prod /beta /release
  • The configuration is dynamically adjusted during operation. It is no longer necessary to write configuration files on each service deployed machine. The service will uniformly pull and configure its own information from the configuration center
  • When the configuration changes, the service does not need to restart, it can sense the change of the configuration and apply the new configuration
  • Expose the configuration information in the form of REST interface

9.1.4 integration of spring cloud config distributed configuration center and GitHub

Because spring cloud config uses git to store configuration files by default (there are other ways, such as self-contained SVN and local files), Git is the most recommended and is accessed in the form of http / https.

9.2 SpringCloud Config server configuration

9.2.1 build git warehouse remotely

  • Create a repository springcloud config on gitee

  • Create local git warehouse and clone

  • Create an application in the local warehouse YML and push

    spring:
      profiles:
        active:
        - dev
    ---
    spring:
      profiles: dev     #development environment 
      application: 
        name: microservicecloud-config-atguigu-dev
    ---
    spring:
      profiles: test   #testing environment
      application: 
        name: microservicecloud-config-atguigu-test
    #  Save in UTF-8 format
    
    • git add .
    • git commit -m "init file"
    • git push origin master

9.2.2 create springcloud-config-3344 module

  • Add pom support

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-config-3344</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-config-server</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-hystrix</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jetty</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-test</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    
  • Modify yml

    server:
      port: 3344
    
    spring:
      application:
        name: springcloud-config
      cloud:
        config:
          server:
            git:
              #uri: git@gitee.com:huebry/springcloud-config.git #gitee warehouse
              uri: https://gitee.com/huebry/springcloud-config.git
    
  • Create main startup class Config_3344_StartSpringCloudApp and add the annotation @ enableconfigureserver

  • Modify the hosts file and add the mapping 127.0.0.1 config-3344 com

  • Start the project to view

    • http://config-3344.com:3344/application-dev.yml
    • http://config-3344.com:3344/application-test.yml
    • http://config-3344.com:3344/application-xxx.yml (nonexistent configuration)

9.2.3 configuring read rules

There are three ways to write yml

  • /{application}-{profile}.yml
    • http://config-3344.com:3344/application-dev.yml
    • http://config-3344.com:3344/application-test.yml
    • http://config-3344.com:3344/application-xxx.yml (nonexistent configuration)
  • /{application}/{profile}[/{label}]
    • http://config-3344.com:3344/application/dev/master
    • http://config-3344.com:3344/application/test/master
    • http://config-3344.com:3344/application/xxx/master (nonexistent configuration)
  • /{label}/{application}-{profile}.yml
    • http://config-3344.com:3344/master/application-dev.yml
    • http://config-3344.com:3344/master/application-test.yml
    • http://config-3344.com:3344/master/application-xxx.yml (nonexistent configuration)

9.3 SpringCloud Config client configuration and testing

9.3.1 upload the configuration file springcloud config client to the remote warehouse yml

spring:
  profiles:
    active:
    - dev
---
server:
  port: 8201
spring:
  profiles: dev
  application:
    name: microservicecloud-config-client
eureka:
  client:
    service-url:
      defaultZone: http://eureka-dev.com:7001/eureka/
---
server:
  port: 8202
spring:
  profiles: test
  application:
    name: microservicecloud-config-client
eureka:
  client:
    service-url:
      defaultZone: http://eureka-test.com:7001/eureka/

9.3.2 create springcloud-config-client-3355 project

  • Import pom

    <?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>springcloud</artifactId>
            <groupId>cn.hubery</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-config-client-3355</artifactId>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-hystrix</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jetty</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-test</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    
  • Create bootstrap yml

    spring:
      cloud:
        config:
          name: springcloud-config-client #The resource name that needs to be read from github. Note that there is no yml suffix
          profile: dev #Configuration items for this visit
          label: master
          uri: http://config-3344.com:3344 # after starting this micro service, go to service 3344 first and get the service address of GitHub through SpringCloudConfig
    
    • applicaiton.yml is a user level resource configuration item

    • bootstrap.yml is system level with higher priority

      Spring Cloud will create a Bootstrap context as the parent context of the Application Context of spring application. During initialization, Bootstrap context is responsible for loading configuration properties from external sources and parsing the configuration. The two contexts share an Environment obtained from the outside. Bootstrap properties have high priority and are not overridden by local configuration by default. Bootstrap context and Application Context have different conventions, so a bootstrap is added YML file to ensure the separation of Bootstrap context and Application Context configuration.

  • Create a new application yml

    spring:
      application:
        name: springcloud-config-client
    
  • Modify the hosts file and add the mapping 127.0.0.1 client config com

  • Create a new rest class and verify whether the configuration can be read from GitHub

    //Verify that the configuration can be read from GitHub
    @RestController
    public class ConfigClientRest {
    
    
        @Value("${spring.application.name}")
        private String applicationName;
        @Value("${eureka.client.service-url.defaultZone}")
        private String eurekaServers;
        @Value("${server.port}")
        private String port;
    
        //Verify that the configuration can be read from GitHub
        @RequestMapping("/config")
        public String getConfig() {
            String str = "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
            System.out.println("******str: " + str);
            return "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
        }
    }
    
  • Add main startup class

  • test

    • Start the Config configuration center 3344 microservice and conduct self-test- http://config-3344.com:3344/application-dev.yml
    • Start 3355 as a Client to prepare for access
    • bootstrap. What is the value of the profile and what is read from the hub
      • If it is currently profile: dev
        • By default, the corresponding port of dev on github is 8201
        • http://client-config.com:8201/config
      • If it is currently profile: test
        • The default port of test on github is 8202
        • http://client-config.com:8202/config

The client 3355 successfully accesses SpringCloud Config3344 and obtains configuration information through GitHub

9.4 SpringCloud Config configuration practice

9.4.1 current situation

  • The Config server configuration is OK and the test passes. We can modify the configuration with config+GitHub and obtain the content

  • At this time, we make a eureka service + a Dept accessed microservice to unify the configuration of the two microservices. Due to the acquisition of github, we can realize unified configuration and distributed management and complete the change of multiple environments

9.4.2 practical steps

  1. Git profile local configuration

    • Create two files

      • springcloud-config-eureka-client. YML - Eureka's server service (Port 7001), as the client side of config

        spring:
          profiles:
            active:
            - dev
        ---
        server:
          port: 7001 #The registry occupies port 7001, and there must be a space after the colon
        spring:
          profiles: dev
          application:
            name: springcloud-config-eureka-client
        eureka:
          instance:
            hostname: eureka7001.com #There must be a space after the colon
          client:
            register-with-eureka: false #The current Eureka server is not registered in the service list
            fetch-registry: false #Do not obtain registration information through eureka
            service-url:
              defaultZone: http://eureka7001.com:7001/eureka/
        ---
        server:
          port: 7001 #The registry occupies port 7001
          
        spring:
          profiles: test
          application:
            name: springcloud-config-eureka-client
            
        eureka:
          instance:
            hostname: eureka7001.com #There must be a space after the colon
          client:
            register-with-eureka: false #The current Eureka server is not registered in the service list
            fetch-registry: false #Do not obtain registration information through eureka
            service-url:
              defaultZone: http://eureka7001.com:7001/eureka/
        
      • springcloud-config-dept-client.yml -- service provider, as the client side of config

        spring:
          profiles:
            active: 
            - dev
        ---
        server:
          port: 8001
          
        spring:
          profiles: dev
          application:
            name: springcloud-config-dept-client  #Name of exposed microservices
          datasource:
            type: com.alibaba.druid.pool.DruidDataSource            # Current data source operation type
            driver-class-name: org.gjt.mm.mysql.Driver              # mysql driver package
            url: jdbc:mysql://localhost:3306/db01? & useencoding # SSL database name = true # code = false      
            username: root
            password: root
            dbcp2:
              min-idle: 5                                           # Minimum number of maintained connections in the database connection pool
              initial-size: 5                                       # Number of initialized connections
              max-total: 5                                          # maximum connection
              max-wait-millis: 200                                  # Maximum timeout waiting for connection acquisition
        
        mybatis:
          config-location: classpath:mybatis/mybatisConfig.xml        # Path of mybatis configuration file
          type-aliases-package: cn.hubery.springcloud.entities       # Package of all Entity alias classes
          mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper Mapping file
        
        eureka:
          client: #The client is registered in the eureka server list
            service-url:
              #defaultZone: http://localhost:7001/eureka/
              defaultZone: http://eureka7001.com:7001/eureka/
          instance:
            instance-id: dept-8001.com  #Custom server host alias
            prefer-ip-address: true #The access path can display the IP address
        info:
          app.name: huebry-springcloud
          company.name: www.huberytu.cn
          build.artifactId: $project.artifactId$
          build.version: $project.version$
          
        ---
        server:
          port: 8001
          
        spring:
          profiles: test
          application:
            name: springcloud-config-dept-client  #Name of exposed microservices
          datasource:
            type: com.alibaba.druid.pool.DruidDataSource            # Current data source operation type
            driver-class-name: org.gjt.mm.mysql.Driver              # mysql Driver package
            url: jdbc:mysql://localhost:3306/db02?useUnicode=true&characterEncoding=utf-8&useSSL=false            # Database name      
            username: root
            password: root
            dbcp2:
              min-idle: 5                                           # Minimum number of maintained connections in the database connection pool
              initial-size: 5                                       # Number of initialized connections
              max-total: 5                                          # maximum connection
              max-wait-millis: 200                                  # Maximum timeout waiting for connection acquisition
        
        mybatis:
          config-location: classpath:mybatis/mybatisConfig.xml        # mybatis Path of configuration file
          type-aliases-package: cn.hubery.springcloud.entities       # Package of all Entity alias classes
          mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper mapping file
        
        eureka:
          client: #The client is registered in the eureka server list
            service-url:
              #defaultZone: http://localhost:7001/eureka/
              defaultZone: http://eureka7001.com:7001/eureka/
          instance:
            instance-id: dept-8001.com  #Custom server host alias
            prefer-ip-address: true #The access path can display the IP address
        info:
          app.name: huebry-springcloud
          company.name: www.huberytu.cn
          build.artifactId: $project.artifactId$
          build.version: $project.version$
        
  2. eureka server in Config version

    • New project springcloud-config-eureka-client-7001

    • pom file

      <?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>springcloud</artifactId>
              <groupId>cn.hubery</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>springcloud-config-eureka-client-7001</artifactId>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-config</artifactId>
              </dependency>
              <!--eureka Server-->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-eureka-server</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>springloaded</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-devtools</artifactId>
              </dependency>
          </dependencies>
      </project>
      
    • bootstrap.xml and application yml

      # bootstrap.xml
      spring:
        cloud:
          config:
            name: springcloud-config-eureka-client     #The resource name that needs to be read from github. Note that there is no yml suffix
            profile: dev
            label: master
            uri: http://config-3344. COM: 3344 #springcloudconfig service address
      
      #application.yml
      spring:
        application:
          name: springcloud-config-eureka-client
      
    • Add main startup class Config_Git_EurekaServerApplication

    • test

      • Start the springcloud-config-3344 microservice first to ensure that the overall configuration of Config is OK
      • Restart the springcloud-config-eureka-client-7001 microservice
      • http://eureka7001.com:7001/ -------The eurek home page appears to indicate successful startup
  3. dept micro service in Config version

    • After referring to the previous 8001 copy, create a new project springcloud-config-dept-client-8001

    • Increase pom dependency

      <?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>springcloud</artifactId>
              <groupId>cn.hubery</groupId>
              <version>1.0-SNAPSHOT</version>
          </parent>
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>springcloud-config-client-provider-dept-8001</artifactId>
      
          <dependencies>
              <dependency>
                  <groupId>cn.hubery</groupId>
                  <artifactId>springcloud-api</artifactId>
                  <version>1.0-SNAPSHOT</version>
              </dependency>
      
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
              </dependency>
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
              </dependency>
              <dependency>
                  <groupId>com.alibaba</groupId>
                  <artifactId>druid</artifactId>
              </dependency>
              <dependency>
                  <groupId>ch.qos.logback</groupId>
                  <artifactId>logback-core</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.mybatis.spring.boot</groupId>
                  <artifactId>mybatis-spring-boot-starter</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-jetty</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-test</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>springloaded</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-devtools</artifactId>
              </dependency>
      
              <!--Check in Eureka Registration Center-->
              <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-eureka</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-config</artifactId>
              </dependency>
              <!--boot Supervisor monitoring and information configuration in-->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-actuator</artifactId>
              </dependency>
          </dependencies>
      
      </project>
      
    • bootstrap.yml and application yml

      #bootstrap.yml
      spring:
        cloud:
          config:
            name: springcloud-config-dept-client #The resource name that needs to be read from github. Note that there is no yml suffix
            #Take whatever profile configuration is dev or test
            #profile: dev
            profile: dev
            label: master
            uri: http://config-3344. COM: 3344 #springcloudconfig service address
      
      #application.yml
      spring:
        application:
          name: springcloud-config-dept-client
      
    • Other classes directly use 8001 items

    • test

      • test configuration access: http://localhost:8001/dept/list ----You can see that the database configuration is 02
      • dev configuration access: http://localhost:8001/dept/list ----You can see that the database configuration is 01

9.5 summary

Distributed configuration (config) is to use a ConfigServer (3344) service to connect to the remote warehouse, where the config configuration file corresponding to the service is stored. In this way, under the condition of using the distributed configuration service, each micro service does not need to provide more complex configuration files. It only needs to point to the ConfigServer service (spring.cloud.config.uri attribute) and specify the configuration file name in the remote warehouse (spring.cloud.config.name attribute).

Keywords: Java

Added by iShaun on Tue, 08 Mar 2022 05:59:54 +0200