springCloud Netflix complete learning

SpringCloud

  • It is an ecosystem, not a technology, used to solve the following problems

Four core issues of microservices:

  1. There are many services. How can customers access them?
  2. With so many services, how can services communicate?
  3. There are too many services. How to manage them?
  4. What if the service hangs up?

Solution:

  1. spring Cloud NetFix: a one-stop solution
    • api gateway: zuul component
    • Feign --HttpClient -- Http communication mode, synchronization, blocking problems
    • Service registration: Eureka
    • Circuit breaker mechanism: Hystrix
  2. Dubbo Zookeeper: semi automatic
    • api: No, third-party components
    • Dubbo: Rpc communication framework, asynchronous
    • Service registration: zookeeper
    • Circuit breaker mechanism: No, with the help of Hystrix
  3. Spring Cloud Alibaba: a one-stop solution

1. What is micro service?

2. How do microservices communicate?

  • http communication protocol, RPC communication

3. What is the difference between springcloud and dubbo?

  • Springcloud is an ecosystem. It has its own gateway zuul component. dubbo does not have it and can only rely on a third party. feign uses http synchronous communication, which will be blocked, while dubbo uses rpc communication, which is asynchronous and non blocking; The service registration of springcloud is Eureka, the service registration of dubbo is zookeeper, and dubbo has no circuit breaker mechanism
  • The biggest difference: SpringCloud abandons Dubbo's RPC communication and uses HTTP based RESTful methods

4.springboot and springcloud, talk about their understanding?

  • Springboot is a scaffold for rapid construction. springcloud is used to solve the problems caused by distribution, such as communication, how to access, fuse problems, and build websites based on springboot
  • springBoot focuses on the rapid and convenient development of individual micro services, and springCloud focuses on the overall service governance framework
  • springCloud relies on springBoot

5. What is service fusing? What is service degradation?

6. What are the advantages and disadvantages of microservices?

7. Micro service technology stack?

8.eureka and zookeeper can provide service registration and discovery functions. Tell me the difference between the two?

1. Microservices

Microservice: it emphasizes the size of services, focuses on a certain point, and is a service application that specifically solves a certain problem / provides landing corresponding services

Microservice architecture: a new form of architecture that advocates dividing a single application into a group of small services, which coordinate and cooperate with each other to provide ultimate value to users.

1.1. Advantages and disadvantages of microservice

advantage:

  1. Each service is cohesive and small enough to focus on a specific business function or business requirement
  2. Development is simple, development efficiency is improved, and a service may be dedicated to something
  3. Microservices can be developed independently by small teams
  4. Microservices are loosely coupled and independent in both development and deployment stages
  5. Microservices are just the code of business logic and will not be mixed with HTML, CSS or other interfaces
  6. Each microservice has its own storage capacity. It can have its own database or a unified database

Disadvantages:

  1. Developers have to deal with the complexity of distributed systems
  2. The difficulty of multi service operation and maintenance. With the increase of services, the pressure of operation and maintenance also increases
  3. System deployment dependency
  4. Communication cost between services
  5. Data consistency

1.2 microservice technology stack

Microservice entryLanding technology
Service developmentSpringBoot,Spring,SpringMVC
Service configuration and managementArchius of Netfix, Diamond of Alibaba, etc
Service registration and discoveryEureka,Consul,zookeeper
Service invocationRest,RPC,gRPC
Service fuseHtstrix,Envoy
load balancing Ribbon Nginx
Service interface call (simplified tool for client to call service)Fegin
Message queueKafka RabbitMQ ActiveMQ
Service configuration center managementSpringCloudConfig Chef
Service routing (API gateway)Zuul
Service monitoringZabbix Nagios Metrics Specatator
Full link trackingZipkin Brave Dapper
Service deploymentDocker OpenStack Kubernetes
Data flow operation development packageSpringcloud stream (encapsulate sending and receiving messages with redis, rabbit kafka, etc.)
Event message busSpringCloud Bus

1.3 why choose SpringCloud as the technical architecture

  1. Selection basis

    • Overall solution and framework maturity
    • Community heat
    • Maintainability
  2. What is the current micro service architecture of IT companies?

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

Function point / service frameworkNetfix/SpringCloudMotangRPCThriftDubbo/DubboX
Function positioningComplete microservice frameworkRPC framework, but it integrates ZK or consult to realize basic service registration / discovery in cluster environmentRPC frameworkRPC frameworkService Framework
Support RestYes, Ribbonnononono
Support RPCnoYes (Hession2)yesyesyes
Support for languagesYes (Rest form)noyesyesno
load balancing Yes (server zuul+ client Ribbon), zuul service, dynamic routing, cloud load balancing Eureka (for the middle service layer)Yes (client)nonoYes (client)
Configure servicesNetfix archhaius, springcloud config server centralized configurationYes (zookeeper improved)nonono
Service call chain monitoringYes (zuul), zuul improves compilation services, API gatewaynononono
High availability / fault toleranceYes (server Hystrix - client Ribbon)Yes (client)nonoYes (client)
Typical application casesNetfixSinaGoogleFacebook
Community activityhighcommonlyhighcommonly
otherSpringCloudBus brings more management breakpoints to our applicationsSupport degradationNetfix internal redevelopment integration gRPCIDL definitionThere are many companies practicing

1.4 relationship between springcloud and SpringBoot

  • springBoot focuses on developing individual micro services quickly and easily
  • springCloud is a micro service coordination and management framework that focuses on the overall situation. It integrates and manages individual micro services developed by springBoot, and provides integrated services between micro services: configuration management, service discovery, circuit breaker, routing, micro agent, event bus, global lock, decision election, distributed session and so on
  • springBoot can be used independently of springCloud, but springCloud cannot be used without springBoot
  • springBoot focuses on the rapid and convenient development of individual micro services, and springCloud focuses on the overall service governance framework

1.5 Dubbo and SpringCloud technology selection

  1. Distributed + service governance Dubbo

Currently mature traditional Internet Architecture: application service splitting + message middleware

  1. Comparison between Dubbo and SpringCloud

Community activity:

  • https://github.com/dubbo
  • https://github.com/spring-cloud

result:

DubboSpringCloud
Service registryzookeeperSpring Cloud Netfix Eureka
Service scheduling modeRPCRest API
Service monitoringDubbo-monitorSpring Boot Admin
Circuit breakerimperfectSpring Cloud Netfix Hystrix
Service gatewaynothingSpring Cloud Netfix Zuul
Distributed configurationnothingSpring Cloud Config
Service trackingnothingSpring Cloud Seluth
Message busnothingSpring Cloud Bus
data streamnothingSpring Cloud Stream
Batch tasknothingSpring Cloud Task

The biggest difference: SpringCloud abandons Dubbo's RPC communication and uses HTTP based RESTful methods

2. What is SpringCloud

spring official website: Spring Cloud

springCloud Chinese documents: Spring Cloud Dalston Chinese document reference manual Chinese version

Chinese API documents: Spring Cloud Netflix Chinese document reference manual Chinese version

springCloud China Community: http://springcloud.cn/

springCloud Chinese website: https://springcloud.cc

2.1 what can springcloud do

  • Distributed/versioned configuration
  • Service registration and discovery
  • Routing route
  • Service to service calls service to service calls
  • Load balancing configuration
  • Circuit Breakers
  • Global locks
  • Distributed messaging

2.2 Spring Cloud version selection

spring BootSPring Cloudrelationship
1.2.xAngle versionCompatible with Spring Boot 1.2.x
1.3.xBrixton versionCompatible with spring Boot 1.3.x 1.4.x
1.4.xCamden versionCompatible with spring Boot 1.4.x 1.5.x
1.5.xDalston1.5.x incompatible with 2.0.x
1.5.xEdgware1.5.x incompatible with 2.0.x
2.0.xFinchleyCompatible with 2.0.x incompatible with 1.5.x
2.1.xGreenwich
2.2.xHoxton.SR122.2.0 — 2.4.0
2.4.x2020.0.52.4.0 — 2.6.0
2.6.x2021.0.02.6.1 — 2.6.4

2.3 Engineering

Parent project: import dependencies

<!--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>
        <lombok.version>1.18.24</lombok.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR12</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--springBoot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--database-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.29</version>
            </dependency>
            <!--data source-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.8</version>
            </dependency>
            <!--springboot starter-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
            <!--log4j-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.2.11</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

 <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Springcloud API: the first micro service, just pojo entity class

package com.liu.springCloud.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@NoArgsConstructor
@Accessors(chain = true) //Support chain writing
public class Dept implements Serializable {
    //Dept entity class orm class table relationship mapping
    private Long deptno; //Primary key auto increment without writing
    private String dname;

    //Which database field does this data exist in? One service corresponds to one database. The same information may exist in different databases
    private String db_source; //Automatic generation

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

Dependency configuration in sub module:

  • The dependency required by the current module itself. If the version has been configured in the parent dependency, there is no need to write it here
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springCloud-01</artifactId>
        <groupId>com.liu</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-01-api</artifactId>

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

</project>

springcloud-provider-dept-8001: the second micro service, provider

Import dependency

<dependencies>
                <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
    	 <!--Improve monitoring information-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
         </dependency>
        <!--You need to get the entity class and configure it api module-->
        <dependency>
            <groupId>com.liu</groupId>
            <artifactId>springcloud-01-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--jetty-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <!--Hot deployment tools-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

application.yaml

server:
  port: 8081
mybatis:
  type-aliases-package: com.liu.springCloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456789
#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/

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>
    
    <typeAliases>
        <package name="com.liu.pojo"/>
    </typeAliases>

</configuration>

mapper interface

@Mapper
@Repository
public interface DeptDao {

    public boolean addDept(Dept dept);

    public Dept queryById(Long id);

    public List<Dept> queryAll();
}

mapper.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.liu.springcloud.dao.DeptDao">
    
    <insert id="addDept" parameterType="Dept">
        insert into db01.dept(dname, db_source)
        values (#{dname},#{db_source});
    </insert>

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

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

</mapper>

service layer

public interface DeptService {
    public boolean addDept(Dept dept);

    public Dept queryById(Long id);

    public List<Dept> queryAll();
}

service implementation class

@service
public class DeptServiceImpl implements DeptService{

    @Autowired
    public 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();
    }
}

controller layer

//Provide restful services
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

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

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

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

}

Startup class

package com.liu.springcloud;

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

//Startup class
@SpringBootApplication
@EnableEurekaClient //Automatically register in eureka after the service is started
public class DeptProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider_8001.class,args);
    }
}

The third micro service: springcloud-consumer-dept-80 consumers

Import dependency

<!--Entity class+web-->
    <dependencies>
        <dependency>
            <groupId>com.liu</groupId>
            <artifactId>springcloud-01-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

application.yaml

server:
  port: 80

Manually inject resttemplate, self built under config directory

@Configuration
public class ConfigBean {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

controller

package com.liu.springcloud.controller;

import com.liu.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 {

    //Consumers should not have a service layer
    //RestTemplate: there are many calls between methods
    //(url, entity: map, class<t> responsetype)
    @Autowired
    private RestTemplate restTemplate; //Provide 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("/consumer/dept/query/{id}")
    private Dept dept(@PathVariable("id") Long id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "dept/query/" + id, Dept.class);
    }

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

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

}

Startup class

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

3. Eureka service registration and discovery

What is Eureka?

  • Follow AP principles
  • It is a sub module of Netflix. It is a REST based service, which is used to locate services to realize cloud middle tier service discovery and failover. Service registration and discovery are very important for microservices. With service and registration, you can access services only by using the service identifier, without modifying the service call configuration file. Its function is similar to Dubbo's registration center, such as zookeeper.

Principle explanation

  • Basic architecture
    • springcloud encapsulates the eureka module developed by netflix to realize service registration and discovery
    • Using C-S architecture design, EurekaServer is the service registration center as the server with service registration function
    • Other micro services in the system use Eureka's client to connect to EurekaServer and maintain a heartbeat connection. Other modules (zuul) of springCloud can discover other micro services in the system and execute relevant logic through EurekaServer
    • Eureka reports red with two components: EurekaServer and EurekaClient
    • EurekaClient is a Java client, which is used to simplify the interaction of EurekaServer. The client also has a built-in load balancer using polling load algorithm. After starting the application, it will send a heartbeat to EurekaServer. If the heartbeat of a node is not received within multiple heartbeat cycles, EurekaServer will remove the service node from the server Registry (the default cycle is 90s)

  • Three roles
    • Eureka Server: provides service registration and discovery zookeeper
    • Server Provider: register its own service in Eureka so that the consumer can find it
    • Eureka Consumer: the service consumer obtains the list of registered services from Eureka to find the consumer services

Import dependency

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

Configuration file application.yaml

server:
  port: 7001

#eureka configuration
eureka:
  instance:
    hostname: localhost #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: false #If false, it means you are the registry
    service-url: #Monitoring page
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/


Startup class

@SpringBootApplication
@EnableEurekaServer  //The startup class of the server can receive others to register
public class EurekaServer_7001 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer_7001.class,args);
    }
}
  • Start 7001 first, then 8001, and you can find that the registration is entered

Alternate name:

#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    instance-id: springcloud-provider-dept8001 #Modify the default information on eureka

Information in the configuration:

1. Guide bag

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

2. Configuration (basically not configured here)

#info configuration
info:
  app.name: liuxiang-springcloud
  company.name: blog.liu.study

3. Results

View application information:

1. Write controller

 @Autowired
    private DiscoveryClient client;
//Get some information from registered microservices
    @GetMapping("/dept/discovery")
    public Object discovery(){
        //Get a list of microservices
        List<String> services = client.getServices();
        System.out.println("discovery=>service"+services);

        //Get a specific micro service information
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost()+"\t"
                    +instance.getPort()
                    +"\t"+instance.getUri());
        }
        return this.client;
    }

2. Add comments to the startup class

//Startup class
@SpringBootApplication
@EnableEurekaClient //Automatically register in eureka after the service is started
@EnableDiscoveryClient //Service discovery
public class DeptProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider_8001.class,args);
    }
}

3. Results

4. Background display

Self protection mechanism:

By default, when eurekaServer receives the heartbeat of the microservice on the page within a certain event, it will log off the instance (default 90s). When the network partition failure occurs, the microservice and eureka cannot communicate normally. eureka solves it through the self-protection mechanism. In this mode, eureka will protect the information of the service registry and will not delete the data in the registry. After the network is restored, it will automatically exit the self-protection mechanism.

3.1 cluster environment configuration

Binding with each other, one service collapses, and you can access another service

Do domain name mapping under C:\Windows\System32\drivers\etc of this machine!

7001 configuration

server:
  port: 7001

#eureka configuration
eureka:
  instance:
    hostname: eureka7001.com #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: false #If false, it means you are the registry
    service-url:
      #Under single machine
      #Under Cluster: Association
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/


7002

server:
  port: 7002

#eureka configuration
eureka:
  instance:
    hostname: eureka7002.com #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: false #If false, it means you are the registry
    service-url: #Monitoring page
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/


7003

server:
  port: 7003

#eureka configuration
eureka:
  instance:
    hostname: eureka7003.com #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: false #If false, it means you are the registry
    service-url: #Monitoring page
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/


The provider is published to the cluster and configured

server:
  port: 8001
mybatis:
  type-aliases-package: com.liu.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456789
#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept8001 #Modify the default information on eureka
#info configuration
info:
  app.name: liuxiang-springcloud
  company.name: blog.liu.study

4. CAP principle and comparison zookeeper

Review CAP principles

RDBMS(mYSQL,Oracle,sqlServer) ==> ACID

NoSQL(redis,mongdb) ==> CAP

ACID:

  • A: atomicity: success is success, failure is failure
  • C: Consistency: the consistency of business logic will not be destroyed before and after the transaction
  • 1: I solation: transactions are executed concurrently, and one unfinished transaction will not affect another transaction
  • D: durability: once the data is submitted, it will be permanently saved

CAP:

  • C: Consistency strong consistency
  • A: Availability availability
  • P: Partition tolerance

The core of CAP Theory:

  • A distributed system irreversibly meets the three requirements of consistency, availability and partition fault tolerance at the same time
  • 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: meet consistency, partition fault tolerance, and the performance is not very high
    • AP: meet availability and partition fault tolerance

As a service registry, what is the difference between eureka and zookeeper?

A distributed system cannot meet C consistency, a availability and P fault tolerance at the same time

  • zookeeper meets: CP
  • eureka meets: AP

zookeeper guarantees CP

At the expense of availability, it is the CP principle!

When querying the service list from the registry, you can tolerate the registration information returned by the registry a few minutes ago, but you cannot receive the service and directly down it. The service registration function requires higher availability than consistency. However, zk will have a situation. When the master node loses contact with other nodes due to network problems, the remaining nodes will re elect leaders. The problem is that the election leader takes too long, 30s-120s, and the entire zk cluster is unavailable during the election, which leads to the paralysis of the registration service during the election.

Eureka guarantees AP

**All nodes of eureka are equal. Several nodes hang up, which will not affect the work of normal nodes. The remaining nodes are still available to provide registration and query functions** Self protection mechanism:

1.eureka will no longer remove services that should expire because they have not received a heartbeat for a long time from the registry

2. It can still receive the registration and query requests of new services, but it will not be synchronized to other nodes

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

5. Load balancing and Ribbon

What is ribbon?

  • spring cloud ribbon is a set of client load balancing tools based on Netflix Ribbon
  • The main function is to provide the software load balancing algorithm of the client and connect the middle tier services of netflix. The client software component of ribbon provides a series of complete configuration items: connection timeout, Retry, etc. It is to list all the machines behind loadBalancer (LB: load balancer for short) in the configuration file. Ribbon will automatically help you connect these machines based on certain rules (such as simple polling, random).

What can ribbon do?

  • Load balancing: distribute users' requests equally to multiple services, so as to achieve HA (high availability) of the system

  • Commonly used load balancing software: Nginx, Lvs, etc

  • Both dubbo and springCloud provide load balancing, and the load balancing algorithm of springCloud can be customized

  • Simple classification of load balancing:

    • Centralized LB
      • An independent LB facility, such as Nginx, is used between the service consumer and the service provider, which forwards the access request to the service provider
    • Prog LB
      • Integrate LB logic into the consumer, and the consumer will know which addresses are available from the service registry, how to add them, and then select a suitable server from these addresses
      • ribbon belongs to in-process LB, which is a class library integrated into the consumer process, through which the consumer obtains the address of the service provider.

Consumer integration ribbon

Import dependency

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

to configure:

server:
  port: 80
#eureka configuration
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

Annotate the startup class to make it effective

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

Customize the configuration of restTemplate to make it load balanced

@Configuration
public class ConfigBean {
    //Configure load balancing to implement restTemplate
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

In the controller of the client consumer

//When passing through the ribbon, the address here should be a variable, accessed through the service id
//    private static final String REST_URL_PREFIX = "http://localhost:8001";
    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";

5.2. Custom load balancing algorithm

Create a package under the springcloud peer directory

@Configuration
public class LiuRule {
    //Configure load balancing to implement restTemplate
    //IRule
    //Availabilityfiltering rule: it will filter the tripped and crashed services first, and poll the remaining services
    //Roundrobin rule polling
    //RandomRule random
    //RetryRule retry
    @Bean
    public IRule myRule(){
        return new RandomRule();
    }
}

Under the startup class: load the custom class when the microservice is started

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = LiuRule.class)
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

6. Feign load balancing

6.1 introduction

Feign is a declarative web service client, which makes it easier to call between microservices. Leishi calls service in the controller. springCloud integrates Ribbon and Eureka, and provides a load balanced http client when using feign

Just create an interface and how to add annotations!

There are two ways to access microservices:

  • Microservice name (ribbon)
  • Interfaces and annotations (feign)

Using ribbon+restTemplate, and using restTemplate to encapsulate http requests, a set of templated calling methods is formed. However, in the actual development, because there are more than one service dependent calls, often an interface will be called more than once, so usually some client classes will be encapsulated for each service to package the calls of these dependent services.

Under the implementation of Feign, we only need to create an interface and configure it in the way of annotation (similar to the Mapper annotation on Dao interface, now it is a microservice interface, which can be annotated with a Feign annotation)

Import dependency

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

api layer writes service interface for other services to access

@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {

    @GetMapping("/dept/query/{id}")
    public Dept queryById(@PathVariable("id")Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);
}

Consumer Controller layer: implemented by annotation

package com.liu.springcloud.controller;

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

import javax.annotation.Resource;
import java.util.List;

@RestController
public class DeptConsumerController {
   
    @@Resource
    private DeptClientService service = null;

    @RequestMapping("/consumer/dept/query/{id}")
    private Dept dept(@PathVariable("id") Long id) {
        return this.service.queryById(id);
    }

    @RequestMapping("/consumer/dept/add")
    public Boolean add(Dept dept){
        return this.service.addDept(dept);
    }

    @RequestMapping("/consumer/dept/list")
    public List<Dept> list(){
        return this.service.queryAll();
    }

}

Implementation class: annotate

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.liu.springcloud"})
public class FeignDeptConsumer {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer.class,args);
    }
}

Result: the essence is to make the code more readable through eureka and annotations!

7. Service fusing Hystrix (server)

Official document translation website: Hystrix user manual | official document translation - Flash sun - blog Garden (cnblogs.com)

The request flow with good completion is as follows:

When a dependent node fails, the entire user request will be blocked:

During peak traffic, the downtime or delay of a single node will quickly lead to saturation of all service loads. Any node in the application that may access other services through the network may become the source of potential failures. More seriously, it may also cause the delay between services to increase and occupy system resources such as queues and threads, resulting in cascading failures between multiple systems.

All the above failures or delays need a set of management mechanism to make the nodes relatively independent, so that any single node failure will not at least undermine the availability of the whole system.

Service avalanche:

When calling between multiple microservices, suppose that microservice A calls B and C, and B and 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, and then cause system crash, which is the so-called "avalanche effect".

7.1. What is Hystrix

In the distributed environment, it is inevitable to encounter the situation that the dependent services hang up. Hystrix can control the interaction of these distributed systems by increasing the delay tolerance and error tolerance. Hystrix establishes an intermediate layer between services to prevent failures between services, and provides an alternative response (fallback) strategy in case of failure to increase the overall reliability and flexibility of the system, rather than waiting for a long time or throwing exceptions that cannot be handled by the calling method, so as to ensure that the thread of the service caller will not be occupied for a long time.

Use:

  1. service degradation
  2. Service fusing
  3. Service current limit
  4. Near real-time monitoring

7.2 service fusing

  • Circuit breaker mechanism is a microservice link protection mechanism corresponding to avalanche effect
  • Comments on circuit breaker: @HystrixCommand

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. When the microservice call response of the node is normal, reply to the call link.

7.3 Engineering

Import dependency

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

Service provider controller layer

//Provide restful services
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    
    @GetMapping("/dept/query/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public Dept queryById(@PathVariable("id")Long id){
        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("id=>"+id+"  The user does not exist, and the information cannot be found!");
        }
        return dept;
    }

    //alternative method 
    public Dept hystrixGet(@PathVariable("id")Long id){
        return new Dept().setDeptno(id)
                .setDname("id=>"+id+"  The user does not exist, and the information cannot be found!@Hystrix")
                .setDb_source("no this database in MySQL");
    }

}

Startup class: add support for fusing

@SpringBootApplication
@EnableEurekaClient //Automatically register in eureka after the service is started
@EnableDiscoveryClient //Service discovery
@EnableHystrix //Contains @enableclircuitbreaker
public class DeptProviderHystrix_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_8001.class,args);
    }
}

Provider configuration: available display IP preferred IP address: true

#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept8001 #Modify the default information on eureka
    prefer-ip-address: true

7. Service degradation Hystrix (client)

service layer of api

@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {

    @GetMapping("/dept/query/{id}")
    public Dept queryById(@PathVariable("id")Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);
}

fallback factory service degradation of api service layer

package com.liu.springcloud.service;

import com.liu.springcloud.pojo.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.List;

//Downgrade
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory {
    @Override
    public DeptClientService create(Throwable throwable) {
        return new DeptClientService() {
            @Override
            public Dept queryById(Long id) {
                return new Dept().setDeptno(id)
                        .setDname("id=>"+id+"There is no corresponding information. The client provides degraded information. The whole service has been shut down now")
                        .setDb_source("no source");
            }

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

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

Client configuration: enable degradation

server:
  port: 80
#eureka configuration
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
#Enable degradation
feign:
  hystrix:
    enabled: true

Close service provider 8001, result:

Difference between fusing and degradation:

Service fusing: the code is written in the provider, which is equivalent to handling and returning exceptions

  • A service times out or is abnormal, causing a fuse

Service degradation: the code is written in the consumer, and the provider will prompt and return abnormal information after closing the service

  • Considering the overall website request load, a service is fused or closed, and the service is no longer called
  • Prepare a fallbackFactory on the client side, return a default value, and the overall service level will decline

8. Hystrix: Dashboard flow monitoring (customer consumption side)

Establishment project: springcloud consumer hystrix dashboard

Import dependency

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

Configure application.yaml

server:
  port: 9001
hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

Startup class

package com.liu.springcloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;

//Startup class
@SpringBootApplication
@EnableEurekaClient //Automatically register in eureka after the service is started
@EnableDiscoveryClient //Service discovery
@EnableHystrix
public class DeptProviderHystrix_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_8001.class,args);
    }

    //Add a bean of dashboard
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        return registrationBean;
    }
}

Ensure that the service provider has the dependence of monitoring information

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

Result: localhost:9001/hystrix

First initiate a query request to access localhost:8001/actuator/hystrix.stream data will be generated

Again Hystrix Monitor , monitor!

Always loading solution:

  1. Reduce the version of cloud to SR2
  2. Configure in the configuration file of dashboard:
hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

9. Routing gateway zuul

What is zuul?

  • zuul includes two main functions: routing and filtering of requests: the routing forwarding function is responsible for forwarding requests to micro service instances, and the filter function is responsible for intervening in the processing of requests, realizing request verification, service aggregation and other functions.
  • zuul service will eventually register with eureka
  • Provide * *: three functions: proxy + routing + filtering**

Official documents: Spring Cloud Netflix Chinese document reference manual Chinese version

Import configuration:

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

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

Configuration: realize routing and filtering

server:
  port: 9527
spring:
  application:
    name: springcloud-zuul
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: zuul9527.com
    prefer-ip-address: true

info:
  app.name: liu-springcloud
  company.name: blog.liu.com

zuul:
  routes:
    mydept.serviceId: springcloud-provider-dept
    mydept.path: /mydept/**
  ignored-services: springcloud-provider-dept #You can no longer use this path to access

Startup class: @EnableZuulProxy

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

Visit this website to get results: localhost:9527/mydept/dept/query/1

After configuration, implement filtering operation and access localhost:9527/springcloud-provider-dept/dept/query/1 , result does not exist

10. springcloud Config distributed configuration

Problems of configuration files faced by distributed systems

Microservice means to split the business in a single application into a sub service. The strength of each service is small, so there will be a large number of services in the system. Because each service needs the necessary configuration information to run, a set of centralized and dynamic configuration management facilities.

springcloud provides configServer to solve this problem!

What is springcloud config distributed configuration center

Provide centralized external configuration support for microservices in the microservice architecture, and the configuration server provides a centralized external configuration for all links of different microservice applications

springcloud config is divided into two parts: server and client:

Server: the distributed configuration center is an independent micro service application used to connect to the configuration server. The client does not provide access interfaces for obtaining configuration information, encrypting and decrypting information

Client: manage application resources and business-related configuration content through the specified configuration center, and obtain and load information from the configuration center when starting. The configuration server uses git to store configuration information by default, which is helpful for version management of environment configuration.

Use of Git

1. Copy the address from gitee

2. Generate public key

Two files will be generated at C:\Users\liuxiang.ssh on the local machine:.pub is the public key

Put it in the public key on gitee!

3. Create a folder locally to store code, open Git client, right-click Git Bash here, and enter the command

git clone + copied address: shift+ins copy key

success!!! Clone to local

4. Create a new configuration file application.yaml

5. Four steps to upload to the remote warehouse

# Add file
git add .
# View status
git status
# Submit to local warehouse submit and message
git commit -m "first commit"
#push to remote warehouse
git push origin master

10.1 config item (server)

  • Access resources on git through config sever

Import dependency

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

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

to configure

server:
  port: 3344
spring:
  application:
    name: springcloud-config-server
  #Connect to remote warehouse
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/lxxdyy12138/springcloud-config.git

Startup class:

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

visit: localhost:3344/application-dev.yaml

10.2 engineering project (client)

Create a config client file and push it to the remote warehouse!

Import dependencies:

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

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

Configuration: bootstrap.yaml

#System level configuration
spring:
  cloud:
    config:
      uri: http://localhost:3344
      name: config-client #The resource name that needs to be read from git does not need a suffix
      profile: dev
      label: master

application.yaml

#User level configuration
spring:
  application:
    name: springcloud-config-client-3355

Startup class

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

Test class controller

@RestController
public class ConfigController {

    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${eureka.client.service-url.defaultZone}")
    private String eurekaServer;
    @Value("${server.port}")
    private String port;

    @RequestMapping("/config")
    public String getConfig(){
        return "applicationName:"+applicationName+
                "eurekaServer"+eurekaServer+
                "port"+port;
    }

}

Result access:

10.3 remote configuration practice (client)

To create a remote warehouse profile:

spring:
    profiles:
        active: dev
---
server:
  port: 7001
spring:
    profiles: dev
    application:
        name: springcloud-config-eureka
#eureka configuration
eureka:
  instance:
    hostname: eureka7001.com #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: true #If false, it means you are the registry
    service-url:
      #Under single machine
      #Under Cluster: Association
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

---
server:
  port: 7001
spring:
    profiles: test
    application:
        name: springcloud-config-eureka
#eureka configuration
eureka:
  instance:
    hostname: eureka7001.com #Instance name of eureka server
  client:
    register-with-eureka: false #Indicates whether to register yourself with the eureka registry
    fetch-registry: true #If false, it means you are the registry
    service-url:
      #Under single machine
      #Under Cluster: Association
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
spring:
    profiles:
        active: dev

---
server:
  port: 8001
mybatis:
  type-aliases-package: com.liu.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
spring:
  profiles: dev
  application:
    name: springcloud-config-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456789
#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-config-dept8001 #Modify the default information on eureka
    prefer-ip-address: true
#info configuration
info:
  app.name: liuxiang-springcloud
  company.name: blog.liu.study
---
server:
  port: 8002
mybatis:
  type-aliases-package: com.liu.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
spring:
  profiles: test
  application:
    name: springcloud-config-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456789
#eureka configuration: where to register the service
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-config-dept8001 #Modify the default information on eureka
    prefer-ip-address: true
#info configuration
info:
  app.name: liuxiang-springcloud
  company.name: blog.liu.study

push to remote warehouse

Guide bag

 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

to configure:

bootstrap.yaml

spring:
  cloud:
    config:
      name: config-eureka #The name here is the name of the remote warehouse project
      label: master
      profile: dev
      uri: http://localhost:3344 # address of the server accessing the remote warehouse

application.yaml

spring:
  application:
    name: springcloud-config-eureka_7001

server:
port: 8002
mybatis:
type-aliases-package: com.liu.springcloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
profiles: test
application:
name: springcloud-config-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456789
#eureka configuration: where to register the service
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
Instance ID: springcloud config dept8001 \modify the default information on eureka
prefer-ip-address: true
#info configuration
info:
app.name: liuxiang-springcloud
company.name: blog.liu.study

push To remote warehouse

[External chain pictures are being transferred...(img-rczTYae2-1658915772501)]

Guide bag

```xml
 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

to configure:

bootstrap.yaml

spring:
  cloud:
    config:
      name: config-eureka #The name here is the name of the remote warehouse project
      label: master
      profile: dev
      uri: http://localhost:3344 # address of the server accessing the remote warehouse

application.yaml

spring:
  application:
    name: springcloud-config-eureka_7001

Tags: Spring Cloud

Posted by PHP Novice on Sun, 31 Jul 2022 21:50:46 +0530