[crazy God talking about Java] SpringCloud notes (50000 word nanny notes)

Posted by mcollyns on Sun, 12 Dec 2021 23:09:55 +0100

video [crazy God says Java] the latest tutorial of spring cloud, IDEA version
Notes refer to flying man's (filled with many missing knowledge points) https://blog.csdn.net/weixin_43591980/article/details/106255122

Project complete source code

Remember the third company~
Gitee : https://gitee.com/NYNUywg/springcloud

Baidu online disk link: https://pan.baidu.com/s/1SehH1rFgo4s04gv1l0tVyQ
Extraction code: yang

1. Learn the preface

1.1 learning premise

  • Proficient in using SpringBoot microservice rapid development framework
  • Learned about Dubbo + Zookeeper distributed Foundation
  • The computer configuration memory is no less than 8g (my own is 16G)

1.2 article outline

Five components of Spring Cloud

  1. Service registration and discovery - Netflix Eureka

  2. Load balancing:

    • Client load balancing - Netflix Ribbon
    • Server load balancing: - feign (it also depends on the Ribbon, but changes the call method resttemplet to the Service interface)
  3. Circuit breaker - Netflix Hystrix

  4. Service gateway - Netflix Zuul

  5. Distributed configuration - Spring Cloud Config

1.3 common interview questions

1.1 what is micro service?

1.2 how do microservices communicate independently?

1.3 what are the differences between springcloud and Dubbo?

1.4 SpringBoot and SpringCloud, please talk about your understanding of them

1.5 what is service fusing? What is service degradation?

1.6 what are the advantages and disadvantages of microservices? Tell me about the pitfalls you encountered in project development

1.7 what are the microservice technology stacks you know? List one or two

1.8 Eureka and Zookeeper can provide service registration and discovery. Please tell us the difference between them
...

2. Overview of microservices

2.1 what is micro service?

What is micro service?

Microservice architecture is a popular architecture idea in recent years. It is difficult to sum up its concept.

What exactly is a micro service? We hereby quote Martin Fowler, chief scientist of ThoughtWorks, who put forward a paragraph in 2014:

Original text: https://martinfowler.com/articles/microservices.html

Sinicization: https://www.cnblogs.com/liuning8023/p/4493156.html

  • At present, there is no unified and standard definition of microservices in the industry.
  • But generally speaking, microservice architecture is an architecture mode, or an architecture style. Its length divides 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 to build it 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.

From the perspective of Technology:

The core of microservicing is to split 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.

2.2 microservices and microservice architecture

Microservices

It emphasizes the size of services. It focuses on a certain point. It is a service application that specifically solves a problem / provides landing corresponding services. In a narrow sense, it can be regarded as micro service projects in the IDEA or Moudel. The IDEA tool uses independent small Moudel developed by Maven. 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 architecture form was proposed by Martin Fowler in 2014.
Microservice architecture is an architecture model. Its body length divides a single application into a group of small services. Services coordinate and cooperate with each other to provide final value for users. Each service runs in its own independent process. Lightweight communication mechanisms (such as HTTP) are used between services to cooperate with each other. Each service is built around specific businesses and can be independently deployed to the production environment. In addition, unified and centralized service management mechanisms should be avoided as far as possible. For a specific service, Appropriate languages and tools (such as Maven) should be selected to build it according to the business context.

2.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;
  • Development is simple and efficient. 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 the development stage or deployment stage;
  • 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 work results and reflect their value without cooperation;
  • Microservices allow the use and integration of the latest technologies;
  • Microservices are just business logic code 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 have 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;

2.4 what are the micro service technology stacks?

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

2.5 why choose spring cloud as the microservice architecture

  1. Selection basis

    • Overall solution and framework maturity
    • Community heat
    • Maintainability
    • learning curve
  2. What are the current microservice architectures used by major IT companies?

    • Ali: dubbo+HFS
    • JD: JFS
    • Sina: Motan
    • Dangdang: DubboX
  3. Comparison of micro Service Frameworks

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

3. Introduction to spring cloud

3.1 what is spring cloud?

Spring official website: https://spring.io/

3.2 relationship between springcloud and SpringBoot

  • SpringBoot focuses on KAISU's convenient development of individual micro services;
  • 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 among microservices: configuration management, service discovery, circuit breaker, routing, proxy, event stack, global lock, decision-making campaign, distributed session, etc;
  • SpringBoot can be used independently of SpringCloud to develop projects, but SpringCloud is inseparable from SpringBoot and belongs to dependency relationship;
  • SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework;

3.3 Dubbo and SpringCloud technology selection

  1. Distributed + service governance Dubbo
    The current mature Internet architecture, application service splitting + message middleware

  2. Comparison between Dubbo and spring cloud
    Take a look at community activity:

https://github.com/dubbo

https://github.com/spring-cloud
Comparison results:

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 calls, 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 a 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.
Difference between brand machine and assembly machine
The difference between community support and renewal

Conclusion: the problem domains solved by the two are different: Dubbo is positioned as an RPC framework, while the goal of spring cloud is a one-stop solution under the microservice architecture.

3.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.5 spring cloud Download

Official website: http://projects.spring.io/spring-cloud/

The version number is a little special:

Instead of naming the version number by numerical number, SpringCloud uses the name of London underground station, and corresponds to the version time order according to the alphabet. For example, the earliest real version is Angel, the second real version is Brixton, followed by Camden, Dalston and Edgware. At present, the latest is Hoxton SR4 CURRENT GA general stable version.

Self study reference books:

  • SpringCloud Netflix Chinese Documentation: https://springcloud.cc/spring-cloud-netflix.html
  • SpringCloud Chinese API document (official document translation): https://springcloud.cc/spring-cloud-dalston.html
  • SpringCloud China Community: http://springcloud.cn/
  • SpringCloud Chinese website: https://springcloud.cc

4. Construction of spring cloud rest learning environment: Service Provider

4.1 introduction

  • We will use a Dept Department module as a general case of micro services. The Consumer consumer (Client) calls the services provided by the Provider (Server) through REST.
  • Review the previous knowledge of Spring, Spring MVC, Mybatis, etc.
  • Review of Maven's subcontracting module architecture.
A simple Maven The module structure is as follows:
-- app-parent: A parent item(app-parent)Aggregated many subprojects(app-util\app-dao\app-web...)
  |-- pom.xml
  |
  |-- app-core
  ||---- pom.xml
  |
  |-- app-web
  ||---- pom.xml
  ......

A parent project has multiple Moudule sub modules

MicroServiceCloud has three sub modules under the parent project for the first time

  • Microservicecloud API [encapsulated overall entity / interface / public configuration, etc.]
  • microservicecloud-consumer-dept-80 [service provider]
  • microservicecloud-provider-dept-8001 [serving consumers]

4.2 spring cloud version selection

SpringCloud: Hoxton.SR1
SpringBoot : 2.2.5.RELEASE
Otherwise, an error may be reported

4.3 create parent project

  • Create a new parent project springcloud. Remember that packaging is a pom mode
  • It is mainly to define POM files and uniformly extract jar packages common to subsequent sub modules, which is similar to an abstract parent class
<?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>com.yang</groupId>
    <artifactId>springcloud</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--Packaging method  pom-->
    <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-alibaba-dependencies</artifactId>
                <version>0.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--springCloud Dependence of-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--SpringBoot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--database-->
            <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.10</version>
            </dependency>
            <!--SpringBoot starter-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
            <!--Log test~-->
            <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>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

Create a database db01 table dept

CREATE DATABASE /*!32312 IF NOT EXISTS*/`db01` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `db01`;
CREATE TABLE `dept` (
  `deptno` int(11) NOT NULL AUTO_INCREMENT,
  `dname` varchar(60) DEFAULT NULL,
  `db_source` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`deptno`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Department table';
INSERT INTO dept (dname,db_source) VALUES ('Development Department',DATABASE());
INSERT INTO dept (dname,db_source) VALUES ('Ministry of Personnel',DATABASE());
INSERT INTO dept (dname,db_source) VALUES ('Finance Department',DATABASE());
INSERT INTO dept (dname,db_source) VALUES ('Marketing Department',DATABASE());
INSERT INTO dept (dname,db_source) VALUES ('Operation and maintenance department',DATABASE());

Create a database connection in IDEA

Create spring cloud API
Import dependency

<dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

Create Dept
I don't know why lombok import will cause the subsequent web page query to fail, so honestly use alt+ins

package com.yang.springcloud.pojo;


import lombok.experimental.Accessors;

import java.io.Serializable;


@Accessors(chain = true)//Chain writing
public class Dept implements Serializable {//Dept entity class orm class table relation mapping

    private Long deptno;//Primary key
    private String dname;

    //Which database field does this data exist ~ micro service, a service corresponds to a database, and the same information may exist in different databases
    private String db_source;

    public Dept() {
    }

    public Dept(String dname) {
        this.dname = dname;
    }

    public Dept(Long deptno, String dname, String db_source) {
        this.deptno = deptno;
        this.dname = dname;
        this.db_source = db_source;
    }

    public Long getDeptno() {
        return deptno;
    }

    public void setDeptno(Long deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getDb_source() {
        return db_source;
    }

    public void setDb_source(String db_source) {
        this.db_source = db_source;
    }
    /*
     * Chain writing:
     * Dept dept = new Dept();
     * dept.setDeptNo(11).setDname('sss').setDb_source('001');
     *
     * */
}

Create springcloud-provider-dep-8001

Configure application yml

server:
  port: 8001

#mybatis configuration
mybatis:
  type-aliases-package: com.yang.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

#spring configuration
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSourceC3P0Adapter
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--Enable L2 cache-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

DeptDao.java

package com.yang.springcloud.dao;

import com.yang.springcloud.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;
@Mapper
@Repository
public interface DeptDao {

    public boolean addDept(Dept dept);

    public Dept queryById(Long id);

    public List<Dept> queryAll();

}

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yang.springcloud.dao.DeptDao">

    <insert id="addDept" parameterType="Dept">
        insert into dept (dname,db_source)
        values (#{dname},DATABASE());
    </insert>

    <select id="queryById" resultType="Dept">
        select *
        from dept
        where deptno = #{deptno};
    </select>

    <select id="queryAll" resultType="Dept">
        select * from dept;
    </select>

</mapper>
package com.yang.springcloud.service;

import com.yang.springcloud.pojo.Dept;
import java.util.List;

public interface DeptService {

    public boolean addDept(Dept dept);

    public Dept queryById(Long id);

    public List<Dept> queryAll();
}

package com.yang.springcloud.service;

import com.yang.springcloud.dao.DeptDao;
import com.yang.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService{

    @Autowired
    private DeptDao deptDao;

    @Override
    public boolean addDept(Dept dept) {
        return deptDao.addDept(dept);
    }

    @Override
    public Dept queryById(Long id) {
        return deptDao.queryById(id);
    }

    @Override
    public List<Dept> queryAll() {
        return deptDao.queryAll();
    }
}

package com.yang.springcloud.controller;


import com.yang.springcloud.pojo.Dept;
import com.yang.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//Provide Restful services
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @PostMapping("/dept/add")
    public boolean addDept( Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id){
        return deptService.queryById(id);
    }

    @GetMapping("/dept/list")
    public List<Dept> queryAll(){
        return deptService.queryAll();
    }
}

Startup class

package com.yang.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//Startup class
@SpringBootApplication
public class DeptProvider_8001 {

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

visit http://localhost:8001/dept/list

4.4 establishment of spring cloud rest learning environment: serving consumers

Create springcloud-consumer-dept-80

Import dependency

<dependencies>
        <dependency>
            <groupId>com.yang</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

Configuration file application yml

server:
  port: 80
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigBean {

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}
package com.yang.springcloud.controller;

import com.yang.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class DeptConsumerController {

    //Understanding: consumers should not have a service layer
    //RestTemplate ...  We can call it directly!
    //(url, entity: map, class < T > responsetype)
    @Autowired
    private RestTemplate restTemplate;//It provides a variety of convenient methods to access remote http services and a simple Restful service template~


    private static final String REST_URL_PREFIX = "http://localhost:8001";

    @RequestMapping("/customer/dept/add")
    public boolean add(@RequestBody Dept dept) {
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
    }

    @RequestMapping("/customer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id, Dept.class);
    }

    @RequestMapping("/customer/dept/list")
    public List<Dept> list(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class);
    }
}

Startup class

package com.yang.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DeptConsumer_80 {

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

}

5.Eureka service registry

5.1 what is Eureka

  • Netflix follows the API principles when it comes to Eureka
  • Eureka is a sub module of Netflix and one of the core modules. Eureka is a REST based service. It is used to locate services to realize service discovery and failover in the cloud middleware layer. Service registration and discovery are very important for microservices. With service registration and discovery, you can access services only by using the service identifier without modifying the service invocation configuration file, The function is similar to Dubbo's registry, such as Zookeeper

5.2 principle understanding

  • Eureka basic architecture

    • Spring cloud encapsulates the Eureka module developed by Netflix to realize service registration and discovery (compared with Zookeeper)
    • Eureka adopts C-S architecture design. Eureka server is the server of service registration function. It 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 system maintenance personnel can
      EurekaServer is used to monitor the normal operation of various microservices in the system. Some other modules of spring cloud (such as Zuul) can discover other microservices in the system and execute relevant logic through EurekaServer
  • Compare with Dubbo architecture

  • Eureka consists of two components: Eureka Server and Eureka Client

  • Eureka Server provides service registration. After each node is started, it will be registered in Eureka Server. In this way, the service registry in Eureka Server will store the information of all class 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 polling load algorithm. After the application starts, a heartbeat will be sent to EurekaServer (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 (the default cycle is 90s)

  • Three roles

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

5.3 construction steps

1. eureka-server
Create springcloud-eureka-7001
pom.xml configuration

<!--Guide Package~-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <!--Import Eureka Server rely on-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Hot deployment tool-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

application.yml

server:
  port: 7001
# Eureka configuration
eureka:
  instance:
    # Instance name of Eureka server
    hostname: 127.0.0.1
  client:
    # Indicates whether to register yourself with Eureka Registry (this module itself is a server, so it is not required)
    register-with-eureka: false
    # If the fetch registry is false, it means that it is the registry and the client is changed to true
    fetch-registry: false
    # Eureka monitoring page~
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Startup class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

//After startup, access http://localhost:7001/
@SpringBootApplication
@EnableEurekaServer //The startup class of the server can accept others to register
public class EurekaServer_7001 {

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

visit http://localhost:7001/

2.eureka-client

Setting up springloucd-provider-dept-8001
1. Import Eureca dependency

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

2. Add Eureca configuration in application

# Eureka configuration: configure the service registry address
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/

3. Add @ EnableEurekaClient annotation to the main startup class

@SpringBootApplication
// @Enable Eureka client enables Eureka client annotation and automatically registers the service with the registry after the service is started
@EnableEurekaClient
public class DeptProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider_8001.class,args);
    }
}

visit http://localhost:7001/

1. Modify the default description information on Eureka

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    instance-id: springcloud-provider-dept-8001 #Modify the default description information on Eureka


If springcloud-provider-dept-8001 is stopped at this time, the monitoring will start the protection mechanism after 30s:

2. Configure monitoring information about service loading

<!--actuator Improve monitoring information-->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

application. Add configuration in YML

# info configuration
info:
  # Name of the project
  app.name: NYNUywg-springcloud
  # Company name
  company.name: School of computer science and technology, Nanyang Normal University

open

  1. EureKa's 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 the eureka server does not receive the instance heartbeat within a certain period of time, the instance will be deleted from the registry (the default is 90 seconds). However, if a large number of instance heartbeats are lost in a short period of time, the eureka server's self-protection mechanism will be triggered. For example, during development and testing, microservice instances need to be restarted frequently, However, we rarely restart the eureka server together (because the eureka Registry will not be modified during development). When the number of heartbeats received in one minute decreases significantly, the protection mechanism will be triggered. You can see Renews threshold and Renews(last min) in the eureka management interface. When the latter (heartbeat received in the last minute) is less than the former (heartbeat threshold), the protection mechanism will be triggered and a red warning will appear: EMERGENCY!EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT.RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEGING EXPIRED JUST TO BE SAFE. As can be seen from the warning, eureka believes that although it cannot receive the heartbeat of the instance, it believes that the instance is still healthy. eureka will protect these instances and will not delete them from the registry.
  • The purpose of this protection mechanism is to avoid network connection failure. In case of network failure, the microservice and the registry cannot communicate normally, but the service itself is healthy and should not be cancelled. If eureka mistakenly deletes the microservice due to network failure, the microservice will not be re registered with eureka server even if the network is restored, Because the registration request will be initiated only when the micro service is started, and only the heartbeat and service list request will be sent later. In this way, although the instance is running, it will never be perceived by other services. Therefore, when the eureka server loses too many client heartbeats in a short time, it will enter the self-protection mode. In this mode, eureka will protect the information in the registry and will not log off any microservices. When the network fault recovers, eureka will automatically exit the protection mode. The self-protection mode can make the cluster more robust.
  • However, in the development and testing phase, we need to restart publishing frequently. If the protection mechanism is triggered, the old service instance is not deleted. At this time, the request may run to the old instance, and the instance has been closed, which will lead to request errors and affect the development and testing. Therefore, in the development and testing phase, we can turn off the self-protection mode by adding the following configuration to the eureka server configuration file: eureka server. Enable self preservation = false [it is not recommended to turn off the self-protection mechanism]
    For details, please refer to the following blog: https://blog.csdn.net/wudiyong22/article/details/80827594
  1. Register the micro service and get some messages (which will be used by team development)
	/**
     * DiscoveryClient It can be used to obtain some configuration information and get specific micro services!
     */
    @Autowired
    private DiscoveryClient client;
	
	/**
     * Get some registered micro service information ~,
     * @return
     */
    @GetMapping("/dept/discovery")
    public Object discovery() {
        // Get the list of micro services
        List<String> services = client.getServices();
        System.out.println("discovery=>services:" + services);
        // Get a specific microservice information through the specific microservice id, applicaioinName;
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" + // Host name
                            instance.getPort() + "\t" + // Port number
                            instance.getUri() + "\t" + // uri
                            instance.getServiceId() // Service id
            );
        }
        return this.client;
    }


Add @ EnableDiscoveryClient annotation to the main startup class

// @EnableEurekaClient opens the annotation of the service discovery client, which can be used to obtain some configuration information and obtain specific microservices
@EnableDiscoveryClient

visit http://localhost:8001/dept/discovery

5.4 Eureka: cluster environment configuration

1. Initialization
Create s pringcloud-eureka-7002 and springcloud-eureka-7003 modules

  • Add dependency
  • yml configuration
server:
  port: 7002


server:
  port: 7003
  • . Main startup class
    It is the same as pringcloud-eureka-7001

2. Cluster members are interrelated
Configure some custom native names, find the native hosts file and open it


At the end of the hosts file, add the local name to access. The default is localhost

Modify application The configuration of YML, as shown in the figure, is springcloud-eureka-7001 configuration, and springcloud-eureka-7002/springcloud-eureka-7003 can also be modified to their corresponding names

In the cluster, associate springcloud-eureka-7001 with springcloud-eureka-7002, springcloud-eureka-7003, and complete application under springcloud-eureka-7001 YML is as follows

server:
  port: 7001
# Eureka configuration
eureka:
  instance:
    # Instance name of Eureka server
    hostname: eureka7001.com
  client:
    # Indicates whether to register yourself with Eureka Registry (this module itself is a server, so it is not required)
    register-with-eureka: false
    # If the fetch registry is false, it means that it is the registry and the client is changed to true
    fetch-registry: false
    # Eureka monitoring page~
    service-url:
      #Override Eureka's default port and access path -- > http://localhost:7001/eureka/
      # Stand alone: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      # Cluster (Association): 7001, 7002, 7003
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

Spring cloud-eureka-7002 and spring cloud-eureka-7003 are the same, and the other two are associated

Modify Eureka configuration through the yml configuration file under springcloud-provider-dept-8001: configure the service registry address

# Eureka configuration: configure the service registry address
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  #Modify the default description information on Eureka
  instance:
    instance-id: springcloud-provider-dept-8001

In this way, the simulation cluster is set up, and a project can be mounted on three servers and run three eureka

5.5 comparison and Zookeeper differences

1. Review CAP principles

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

NoSQL (Redis\MongoDB) ===> CAP

2. What is acid?

  • A (Atomicity)
  • C (Consistency)
  • I (Isolation)
  • D (Durability)

3. What is cap?

  • C (Consistency) strong consistency
  • A (Availability)
  • P (Partition tolerance)
  • Three in two of CAP: CA, AP, CP

4. The core of cap theory

  • A distributed system cannot meet the three requirements of consistency, availability and partition fault tolerance at the same time
    Root - according to CAP principle, 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

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 distributed systems, we can only trade off between A and C.
  • Zookeeper guarantees CP - > systems that meet consistency and partition fault tolerance, and generally 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, a situation occurs in zookeeper. When the master node loses contact with other nodes due to network failure, the remaining nodes will re elect leaders. The problem is that the election leader takes too long, 30-120s, and the entire 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 a high probability event. 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 registering with an Eureka client, 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 not 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 for 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

6. Ribbon: load balancing (client based)

6.1 load balancing and Ribbon

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. The Ribbon client component provides a series of complete configuration items, such as connection timeout, Retry, etc. To put it simply, list all the machines behind the LoadBalancer (LB: load balancer for short) 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 a custom load balancing algorithm!

What can Ribbon do?

  • LB, load balancer, 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 (high use) of the system.

  • Common load balancing software include Nginx, Lvs, etc.

  • Both Dubbo and spring cloud provide us with load balancing. The load balancing algorithm of spring cloud can be customized.

  • Simple classification of load balancing:

    • Centralized LB

      • That is, an independent LB facility is used between the service provider and the consumer, such as nginx (reverse proxy server), which is responsible for forwarding the access request to the service provider through some policy!
    • Advance program LB

      • Integrate LB logic into the consumer. The consumer knows which addresses are available from the service registry, and then selects an appropriate server from these addresses.
      • Ribbon belongs to in-process LB. it is just a class library integrated into the consumer process. The consumer obtains the address of the service provider through it!

6.2 integrated Ribbon

springcloud-consumer-dept-80 to POM Add Ribbon and Eureka dependencies to XML

<!--Ribbon-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--Eureka: Ribbon Need from Eureka What can I get from the service center-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

In application Configure Eureka in the YML file
Eureka configuration

eureka:
  client:
    register-with-eureka: false # Do not register yourself with Eureka
    service-url: # Access one of the three registries at random
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

The main startup class is annotated with @ EnableEurekaClient to open Eureka

//After the integration of Ribbon and Eureka, the client can call directly without caring about the IP address and port number
@SpringBootApplication
@EnableEurekaClient //Open Eureka client
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class, args);
    }
}

Custom Spring configuration class: configbean Java configuration load balancing to implement RestTemplate

@Configuration
public class ConfigBean {
    //@Configuration -- spring  applicationContext.xml
    @LoadBalanced //Configure load balancing to implement RestTemplate
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

Modify the controller: deptconsumercontroller java

//Ribbon: the address here should be a variable accessed by the service name
//private static final String REST_URL_PREFIX = "http://localhost:8001";
private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";

6.3 load balancing using Ribbon

flow chart:

1. Create two databases: db02 and db03
1. Create two new service providers: springcloud-provider-dept-8003 and springcloud-provider-dept-8002

2. Refer to springcloud-provider-dept-8001 to add POM for the other two clouds XML dependency, mybatis under resourcece and application YML configuration, Java code, modify application 8001 port number and instance ID under YML: springcloud provider dept 8001, database db02,db03, modify the name of the main startup class

3. Start all service tests (determine the number of services to start according to your computer configuration), and access http://eureka7001.com:7002/ View results

visit http://localhost/customer/dept/list




Each visit above http://localhost/consumer/dept/list Random access to a service provider in the cluster is called polling. The polling algorithm can be customized in spring cloud.

6.4 how to switch or customize rules?

Configure in the ConfigBean under the springcloud-provider-dept-80 module and switch to different rules

Random access server

Insert the code slice here@Configuration
public class ConfigBean {
    //@Configuration -- spring  applicationContext.xml
    /**
     * IRule:
     * RoundRobinRule round-robin policy 
     * RandomRule Random strategy
     * AvailabilityFilteringRule :  It will filter out, trip, access the failed service ~, and poll the rest~
     * RetryRule :  The service ~ will be obtained according to the polling first. If the service acquisition fails, it will be performed within the specified time and try again
     */
    @Bean
    public IRule myRule() {
        return new RandomRule();//Use random strategy
        //return new RoundRobinRule();// Use polling policy
        //return new AvailabilityFilteringRule();// Use polling policy
        //return new RetryRule();// Use polling policy
    }
}

Create * * YangRandomRule, YangRule, * * Note: the package should not be the same level as the package where the main startup class is located, but should be the same level as the package where the startup class is located:

MyRule.java

/**
 * @Auther: csp1999
 * @Date: 2020/05/19/11:58
 * @Description: Custom rules
 */
@Configuration
public class MyRule {
    @Bean
    public IRule myRule(){
        return new MyRandomRule();//The default is polling RandomRule, which is now customized as its own
    }
}

The main startup class enables load balancing and specifies a custom MyRule configuration class

//After the integration of Ribbon and Eureka, the client can call directly without caring about the IP address and port number
@SpringBootApplication
@EnableEurekaClient
//The custom Ribbon class can be loaded when the micro service is started (the custom rules will overwrite the original default rules)
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = MyRule.class)//Turn on load balancing and specify custom rules
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class, args);
    }
}

Custom rules (here we refer to the default rule code in the Ribbon and change it slightly): myrandomrule java

public class MyRandomRule extends AbstractLoadBalancerRule {
    /**
     * If each service is accessed 5 times, the next service will be replaced (3 services in total)
     * <p>
     * total=0,Default = 0. If = 5, it points to the next service node
     * index=0,Default = 0, if total=5,index+1
     */
    private int total = 0;//Number of calls
    private int currentIndex = 0;//Who is currently providing services
    //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
    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 = chooseRandomInt(serverCount);// Generating interval random number
            //server = upList.get(index);// Randomly get one from a or living service
            //=====================Custom code=========================
            if (total < 5) {
                server = upList.get(currentIndex);
                total++;
            } else {
                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;
    }
    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }
    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub
    }
}

visit: http://localhost/customer/dept/list
Customize the random access server, but the quick access server will jump!

7.Feign: load balancing (based on the server)

7.1 Feign introduction

Feign is a declarative Web Service client, which makes it easier to call between microservices, similar to the controller calling service. Spring cloud integrates Ribbon and Eureka, and can use Feigin to provide a load balanced http client

Just create an interface and add annotations~
Feign, mainly the community version, is used to interface oriented programming. This is the norm for many developers. There are two methods for invoking microservice access

  • Microservice name [ribbon]
  • Interface and notes [feign]

What can Feign do?

  • Feign aims to make it easier to write Java Http clients
  • Previously, when using Ribbon + RestTemplate, the RestTemplate is used to encapsulate Http requests to form a set of templated calling methods. 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, a client class is 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 interface. Under the implementation of Feign, we only need to create an interface and configure it by annotation (similar to the Mapper annotation on Dao interface in the past, now it is a micro service interface with a Feign annotation on it), The interface binding to the service provider can be completed, which simplifies the development of automatically encapsulating the service call client when using the Spring Cloud Ribbon.

Feign integrates Ribbon by default

  • 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 the Ribbon, Feign only needs to define the service binding interface and realize the service invocation in a declarative way.

7.2 use steps of feign

Create the deptclientserver.com under the spring cloud API Java, adding dependencies

<!--Feign Dependence of-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
// @FeignClient: Micro service client annotation, value: specify the name of the micro service, so that the Feign client can directly find the corresponding micro service
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);
    @GetMapping("/dept/list")
    public List<Dept> queryAll();
    @GetMapping("/dept/add")
    public boolean addDept(Dept dept);
}

Create the springcloud consumer fdept feign module
Copy the POM under the springcloud-consumer-dept-80 module XML, resource, and java code to the spring cloud consumer feign module, and add feign dependencies.

<!--Feign Dependence of-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
@RestController
public class DeptConsumerController {
    @Autowired
    private DeptClientService deptClientService = null;
    /**
     * Add department information to the consumer
     * @param dept
     * @return
     */
    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept) {
        return this.deptClientService.addDept(dept);
    }
    /**
     * The consumer queries the Department information according to the id
     * @param id
     * @return
     */
    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        return this.deptClientService.queryById(id);
    }
    /**
     * Consumer query department information list
     * @return
     */
    @RequestMapping("/consumer/dept/list")
    public List<Dept> list() {
        return this.deptClientService.queryAll();
    }
}
@SpringBootApplication
@EnableEurekaClient
// feign client annotation, and specifies the package to be scanned and the configuration interface DeptClientService
@EnableFeignClients(basePackages = {"com.yang.springcloud.service"})
// Remember not to add this annotation, otherwise 404 cannot be accessed
//@ComponentScan("com.yang.springcloud.service")
public class FeignDeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer_80.class, args);
    }
}

7.3 how to choose feign and Ribbon?

According to 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 the Ribbon, but the latter is in the calling mode, in order to meet the interface calling habits used by some developers!

Let's close the service consumer springcloud-consumer-dept-80 and replace it with springcloud-consumer-dept-feign (port is still 80): (it can still be accessed normally, that is, the calling method is changed compared with the Ribbon)

8. Hystrix: Service fuse

Problems faced by distributed systems

  • There are dozens of dependencies for applications in complex distributed architecture, and each dependency will inevitably fail at some time!

8.1 service avalanche

When calling between multiple microservices, suppose 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 tens of 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 all mean that failures and delays need to be isolated and managed to achieve the failure of a single dependency without affecting the operation of the whole application or system.
We need to get rid of the car!

8.2 what is Hystrix?

Hystrix is an open source library used to deal with the 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 the failure of the whole system service, 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 a service expected and processable 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 cannot be handled by the calling method, This can ensure 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.

8.3 what can hystrix do?

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

When everything is normal, the request flow can be as follows:
When there is a potentially blocking service in many back-end systems, it can block the entire user request:

With the increase of high-capacity traffic, the potential of a single back-end dependency will cause all resources on all servers to saturate in a few seconds.

Every point in the application that may cause network requests through the network or client library is the source of potential failures. Worse than failure, these applications can also lead to increased latency between services, backing up queues, threads, and other system resources, resulting in more cascading failures across systems.

When you wrap each base dependency with Hystrix, the architecture shown in the above diagram changes similar to the following diagram. Each dependency is isolated from each other, limited to the resources it can fill when the delay occurs, and included in the fallback logic, which determines the response to any type of failure in the dependency:
Official website information: https://github.com/Netflix/Hystrix/wiki

8.4 service fuse

What is service?
Circuit breaker mechanism is a microservice link protection mechanism to win 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 wrong response information. After detecting that the microservice call response of the node is normal, restore the call link. 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 fuse mechanism will be started. The annotation of the fuse mechanism is: @ HystrixCommand.

The following problems can be solved by the service provider:

  • 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.

Introductory case
Create a new springcloud provider Dept hystrix-8001 module and copy the POM in springcloud provider Dept – 8001 XML, resource, and Java code to initialize and adjust.

Import hystrix dependencies

<!--Import Hystrix rely on-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

Adjust yml profile

server:
  port: 8001

#mybatis configuration
mybatis:
  # pojo package under spring cloud API module
  type-aliases-package: com.yang.springcloud.pojo
  # Mybatis config. Under this module XML core configuration file classpath
  config-location: classpath:mybatis/mybatis-config.xml
  # mapper configuration file classpath under this module
  mapper-locations: classpath:mybatis/mapper/*.xml

#spring configuration
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
# Eureka configuration: configure the service registry address
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  #Modify the default description information on Eureka
  instance:
    instance-id: springcloud-provider-dept-8001
    #prefer-ip-address: true #After changing to true, the default display is the ip address instead of localhost
# info configuration
info:
  # Name of the project
  app.name: NYNUywg-springcloud
  # Company name
  company.name: School of computer science and technology, Nanyang Normal University

prefer-ip-address: false:

prefer-ip-address: true:

Modify controller

@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    /**
     * Query department information according to id
     * If an exception occurs in the query based on id, follow the alternative code of hystrixGet
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "hystrixGet")
    @RequestMapping("/dept/get/{id}")//Query by id
    public Dept get(@PathVariable("id") Long id){
        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("this id=>"+id+",The user does not exist or the information cannot be found~");
        }
        return dept;
    }
    /**
     * Query alternatives by id (fuse)
     * @param id
     * @return
     */
    public Dept hystrixGet(@PathVariable("id") Long id){
        return new Dept(id,"this id=>"+id+",No corresponding information,null---@Hystrix~","stay MySQL This database does not exist in");
    }
}

Add @ enablercircuitbreaker annotation to the main startup class

@EnableCircuitBreaker // Add a supporting comment for the fuse

visit http://localhost/customer/dept/get/6

Instead of using the fused springcloud provider Dept – 8001 module to access the same address, the following conditions will occur:

Therefore, it is necessary to use fuse in order to avoid errors in the whole application or web page due to exceptions or errors in the background of a micro service

8.5 service degradation

What is service degradation?
Service degradation means that when the server pressure increases sharply, some services and pages are not processed strategically or handled in a simple way according to the actual business conditions and traffic, so as to release server resources to ensure the normal or efficient operation of core business. To put it bluntly, it is to give system resources to high priority services as much as possible.
Resources are limited and requests are unlimited. If the service is not degraded during the concurrency peak period, 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 order to ensure the availability of core function services, some services must be degraded during peak periods. For example, when double 11 is active, all services unrelated to the transaction are downgraded, such as viewing ant deep forest, viewing historical orders, etc.

**What are the main scenarios for 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.

The degradation method can be based on the business, and the service can be delayed. For example, the delay will increase the points for the user, but it will be put into a cache and executed after the service is stable; Or close the service within the granularity, such as the recommendation of relevant articles.

It can be seen from the above figure that when the traffic of service A increases sharply and the traffic of B and C is small at A certain time, in order to alleviate the pressure of service A, B and C need to temporarily close some service functions to undertake some services of A, so as to share the pressure for A, which is called service degradation.

Issues to be considered for 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?

Automatic degradation classification

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

2) 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

3) 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, it will return to the default stock), bottom data (for example, if the advertisement is suspended, it will return some static pages prepared in advance), cache (some cache data previously temporarily stored)

4) Current limit degradation: when second killing or snapping up some restricted goods, the system may crash due to too much traffic. At this time, current limit will be used to limit the traffic. When the current limit threshold is reached, subsequent requests will be degraded; The processing scheme after degradation can be: queuing page (divert the user to the queuing 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).

Introductory case

Create a new degraded configuration class deptclientservicefallbackfactory. In the service package under the springcloud API module java

/**
 * @Auther: A little Yibai
 * @Date: 2021/12/11
 * @Description: Hystrix Service degradation~
 */
@Component
public class DeptClientServiceFallBackFactory implements FallbackFactory {
    @Override
    public Object create(Throwable throwable) {
        return new DeptClientService() {
            @Override
            public Dept queryById(Long id) {
                return new Dept(id,"id=>" + id + "There is no corresponding information. The client provides degraded information. The service has been shut down","no data~");
            }

            @Override
            public List<Dept> queryAll() {
                return null;
            }

            @Override
            public boolean addDept(Dept dept) {
                return false;
            }
        };
    }
}

Specify the degraded configuration class DeptClientServiceFallBackFactory in DeptClientService

@Component //Register in spring container
// @FeignClient: Micro service client annotation, value: specify the name of the micro service, so that the Feign client can directly find the corresponding micro service
//fallbackFactory specifies the degraded configuration class
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)
public interface DeptClientService {

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);
    @GetMapping("/dept/list")
    public List<Dept> queryAll();
    @GetMapping("/dept/add")
    public boolean addDept(Dept dept);
}

Enable demotion in the springcloud consumer dept feign module:

# Enable degraded feign hystrix
feign:
  hystrix:
    enabled: true

Open 7001, springcloud provider dept-8001, springcloud consumer dept feign (not 80), and access http://localhost/consumer/dept/get/1 normal

Turn off 8001 server and refresh

8.6 difference between service fusing and degradation

  • Service fusing - > server: a service timeout or exception 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 a decline in 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) fault, 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.

Fusing, degradation, current limiting:
Fusing: the dependent downstream service failure triggers fusing to avoid causing the system crash; Automatic system execution and recovery
Degradation: services are prioritized, sacrificing non core services (unavailable) to ensure the stability of core services; Considering the overall load;
Flow limit: limit concurrent request access. If the threshold is exceeded, it will be rejected;

8.7 Dashboard flow monitoring

Create a new springcloud consumer hystrix dashboard module
Add dependency

<!--Hystrix rely on-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--dashboard rely on-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--Ribbon-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--Eureka-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--Entity class+web-->
<dependency>
    <groupId>com.haust</groupId>
    <artifactId>springcloud-api</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Hot deployment-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

Main startup class

@SpringBootApplication
// Open Dashboard
@EnableHystrixDashboard
public class DeptConsumerDashboard_9001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumerDashboard_9001.class,args);
    }
}

Add the following code to the main startup class under the springcloud provider Dept hystrix-8001 module to add monitoring

//Startup class
@SpringBootApplication
//Automatically register with Eureka after the service starts
@EnableEurekaClient
//Open the annotation of the service discovery client, which can be used to obtain some configuration information and obtain specific microservices
@EnableDiscoveryClient
// Add a supporting comment for the fuse
@EnableCircuitBreaker
public class DeptProviderHystrix_8001 {

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

    //Add a Servlet
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        //Accessing this page is the monitoring page
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        return registrationBean;
    }
}

open

open http://localhost:8001/actuator/hystrix.stream
http://localhost:9001/hystrix
http://localhost:8001/dept/get/1


Enter the monitoring page:

Quick access

get/1 and get/10 monitors the number of successes and failures

9. Zull routing gateway

9.1 general

What is zuul?
Zull includes two main functions: Request Routing (for jump) 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 request processing process, which is the basis for realizing request verification, service aggregation and other functions. Zuul and Eureka integrate, register zuul as an application under Eureka service governance, and obtain messages of other 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!

What can Zuul do?

  • route
  • filter

9.2 introduction cases

Create a new springcloud zuul module and import dependencies

<dependencies>
    <!--Import zuul rely on-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--Hystrix rely on-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--dashboard rely on-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix-dashboar</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--Ribbon-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--Eureka-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--Entity class+web-->
    <dependency>
        <groupId>com.haust</groupId>
        <artifactId>springcloud-api</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Hot deployment-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

Configure application YML: added zuul configuration

server:
  port: 9527
spring:
  application:
    name: springcloud-zuul #Microservice name
# eureka registry configuration
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance: #id of the instance
    instance-id: zuul9527.com
    prefer-ip-address: true # Display ip
info:
  app.name: yang.springcloud # entry name
  company.name: School of computer science and technology, Nanyang Normal University # corporate name

zuul:
  # Routing related configuration
  # The original access route is www.kuangstudy.com com:9527/springcloud-provider-dept/dept/get/1
  # After zull route configuration, visit www.kuangstudy.com com:9527/mydept/yang/dept/get/1
  routes:
    mydept.serviceId: springcloud-provider-dept # Service provider routing name of eureka registry
    mydept.path: /mydept/** # Change the service provider route name of the eureka registry to a custom route name
      # You can no longer use this path to access, *: ignore and hide all service names~
  ignored-services: "*"
  # Set public prefix
  prefix: /yang

visit http://localhost:7001/

It can be seen that Zull routing gateway is registered in Eureka registry!

The service name is not hidden

After the service name is hidden

We can see that the microservice name is replaced and hidden, replaced by our custom microservice name mydept, and prefixed with yang, so as to encrypt the access of routing fan!

10. Spring Cloud Config distributed configuration

Dalston.RELEASE

Spring Cloud Config provides server and client support for external configurations in distributed systems. With Config Server, you can manage external properties of applications in all environments. The conceptual mappings on the client and server are the same as the Spring Environment and PropertySource abstractions, so they fit well with spring applications, but can be used with any application running in any language. As applications go through the deployment process from developers to test and production, you can manage the configuration between these environments and determine that the application has everything you need to run when migrating. The default implementation of the server storage back end uses git, so it easily supports the configuration environment of the label version and can access various tools for managing content. It's easy to add an alternative implementation and insert it using the spring configuration.

10.1 general

Configuration file 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. Since each service needs the necessary configuration information to run, a set of centralized and dynamic configuration management facilities is essential. spring cloud provides configServer to solve this problem. Each microservice brings an application YML, it's a headache to modify hundreds of configuration files!

What is the spring cloud config distributed configuration center?

spring cloud config provides centralized external support for microservices in the microservice architecture. The configuration server provides a centralized external configuration for all links of different microservice applications.

spring cloud 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 the client with access interfaces such as obtaining configuration information, encryption and decryption information.

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. The configuration server uses git to store configuration information by default, which is helpful for version management of environment configuration. The GIT client tool can be used to manage and access the configuration content conveniently.

What can the spring cloud config distributed configuration center do?

Centralized management profile
Different environments, different configurations, dynamic configuration updates, and 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 configuration changes and apply the new configuration
Expose the configuration information in the form of REST interface

Integration of spring cloud config distributed configuration center and GitHub

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

Introductory case

Put the newly created application.config in the springcloud config folder of the local git warehouse YML submitted to code cloud warehouse:

spring:
  profiles:
    active: dev
    
---
spring:
  profiles: dev
  application:
    name: springcloud-config-dev

---
spring:
  profiles: test
  application:
    name: springcloud-config-test

10.2 server

Create a new springcloud-config-server-3344 module and import POM XML dependency

<dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--config-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <!--eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
    </dependencies>

Create application. Under resource YML configuration file, Spring Cloud Config server provides configuration for remote clients from git repository (required):

server:
  port: 3344
spring:
  application:
    name: springcloud-config-server
  # Connection code cloud remote warehouse
  cloud:
    config:
      server:
        git:
          # Note that it is https, not ssh
          uri: https://gitee.com/NYNUywg/springcloud-config.git
          # You can connect to git through config server to access its resources and configuration~
# If this configuration is not added, the error Cannot execute request on any known server will be reported: the address of the Eureka server connection is incorrect
# Or directly comment out the eureka dependency. eureka is temporarily unavailable here
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

Main startup class config_ Server_ three thousand three hundred and forty-four

@EnableConfigServer // Start the spring cloud config server service
@SpringBootApplication
public class Config_Server_3344 {
    public static void main(String[] args) {
        SpringApplication.run(Config_Server_3344.class,args);
    }
}

The default strategy for locating resources is to clone a git repository (in spring.cloud.config.server.git.uri) and use it to initialize a mini spring application. The Environment of the applet is used to enumerate property sources and publish them through JSON endpoints.

The HTTP service has resources in the following format:

/{
    application}/{profile}[/{label}] //First kind
/{
    application}-{profile}.yml //Second
/{
    label}/{application}-{profile}.yml //Third
/{
    application}-{profile}.properties //Fourth
/{
    label}/{application}-{profile}.properties //Fifth

First:
application}/{profile}[/{label}]
http://localhost:3344/application/test/master

Second:
application}-{profile}.yml
http://localhost:3344/application-dev.yml

Third:
label}/{application}-{profile}.yml
http://localhost:3344/master/application-dev.yml

10.3 client

Put the newly created config client.config in the springcloud config folder of the local git warehouse YML submitted to code cloud warehouse:
Note that there can only be three horizontal -

spring:
  profiles:
    active: dev
    
---
server:
  port: 8201
#spring configuration
spring:
  profiles: dev
  application:
    name: springcloud-provider-dept
    
# Eureka configuration: configure the service registry address
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/
      
---
server:
  port: 8202
#spring configuration
spring:
  profiles: test
  application:
    name: springcloud-provider-dept
    
# Eureka configuration: configure the service registry address
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/


Create a new springcloud-config-client-3355 module and import dependencies

Insert the code slice here<!--config-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-start -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Create an application. Under resources YML and bootstrap YML profile
bootstrap.yml is a system level configuration

System level configuration

spring:
  cloud:
    config:
      name: config-client # The resource name that needs to be read from git without suffix
      profile: dev
      label: master
      uri: http://localhost:3344

application.yml is a user level configuration

User level configuration

spring:
  application:
    name: springcloud-config-client

Create the configclientcontroller under the controller package Java for testing

@RestController
public class ConfigClientController {
    @Value("${spring.application.name}")
    private String applicationName; //Get microservice name
    @Value("${eureka.client.service-url.defaultZone}")
    private String eurekaServer; //Get Eureka services
    @Value("${server.port}")
    private String port; //Get the port number of the server
    @RequestMapping("/config")
    public String getConfig(){
        return "applicationName:"+applicationName +
                "eurekaServer:"+eurekaServer +
                "port:"+port;
    }
}

Main startup class

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

Test:

Start server Config_Server_3344 restart the client configclient_ three thousand three hundred and fifty-five
visit http://localhost:8201/config/

10.4 small cases

Create config-dept.yml and config-eureka.com locally YML and submit to code cloud warehouse

Here, the content of the configuration file is no longer listed, but directly to the code.

Create a new springcloud-config-eureka-7001 module and copy the contents under the original springcloud-eureka-7001 module to this module.

1. Clear the application of this module YML configuration and create a new bootstrap YML connection remote configuration

spring:
  cloud:
    config:
      name: config-eureka # Profile name in warehouse
      profile: dev
      label: master
      uri: http://localhost:3344

2. In POM Add spring cloud config dependency to XML

<!--config-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-config -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>

3. Main startup

@SpringBootApplication
@EnableEurekaServer //The startup class of EnableEurekaServer server can accept others to register~
public class ConfigEurekaServer_7001 {
    public static void main(String[] args) {
        SpringApplication.run(ConfigEurekaServer_7001.class,args);
    }
}

4. Test
Step 1: start Config_Server_3344, and visit http://localhost:3344/master/config-eureka-dev.yml test

Part II: start configurekaserver_ 7001, access http://localhost:7001/ test

Create a new springcloud-config-dept-8001 module and copy the contents of springcloud-provider-dept-8001

Similarly, import the spring cloud config dependency and clear the application YML. Create a bootstrap YML configuration file and configure

spring:
  cloud:
    config:
      name: config-dept
      label: master
      profile: dev
      uri: http://localhost:3344

Main startup class

//Startup class
@SpringBootApplication
//Automatically register with Eureka after the service starts
@EnableEurekaClient
//Open the annotation of the service discovery client, which can be used to obtain some configuration information and obtain specific microservices
@EnableDiscoveryClient
public class ConfigDeptProvider_8001 {

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

Topics: Java Spring Spring Cloud eureka