SpringCloud use and Nacos

Table of contents

1. What is Spring Cloud?

    1.1 Introduction to business scenarios 

    1.2 Service Analysis 

    1.3 Process call

    1.4 Spring Cloud 

2. Spring Cloud Core Components 

    2.1 Eureka

    2.2 Feign

    2.3 Ribbon 

    2.4 Hystrix 

    2.5 Zuul

3. spring Cloud relationship 

   3.1 Spring Cloud Netflix first generation 

   3.2 Spring Cloud Alibaba Second Generation

3.2.1 "Ali Open Source Components"

3.2.2 "Ali Commercialization Components"

4. Common components of SpringCloud

5. Version relationship

    Spring Boot

    Spring Cloud

    Spring Cloud Dependencies

    Spring Cloud Chinese Study Guide

    Spring Cloud Alibaba

6. Version management specification

7. Nacos build

    Nacos official website

   7.1 Configure Nacos database source 

   7.2 Start Nacos and visit the Nacos management page

8. Consumer and producer writing

    8.1 Create a new maven project as the parent project  

    8.1.1 Modify the parent project pom file and add the following code

8.2 Create a new springboot project as a subproject (producer builds Provider)

    8.2.1 Modify and add subproject pom files  

    8.2.2 Modify and add sub-project application.yml file

    8.2.3 Modify and add subproject startup class

8.3 Create a new springboot project as a subproject (consumer builds Consumer)

     8.3.1 Modify and add sub-project pom files

     8.3.2 Modify and add sub-project application.yml file

     8.3.3 Modify and add subproject startup class

9. Start the sub-project Tomcat server and go to the Nacos management page to view the service

10. Call method

     10.1 New sub-project [producer build Provider] Controller module code 

     10.2 Modify and add sub-project [consumer build Consumer] pom file

     10.3 New sub-project [consumer build Consumer] Controller module code 

     10.4 Modify and add sub-project [consumer build Consumer] startup class

     10.5 Start subproject server call and test method


1. What is Spring Cloud?

    1.1 Introduction to business scenarios 

       To develop an e-commerce website, to realize the function of paying orders, the process is as follows: 

  •  After creating an order, if the user pays for the order immediately, we need to update the order status to "Paid"
  •  Deduct the corresponding commodity inventory
  •  Notify the warehouse center for delivery
  •  Add corresponding points to the user's shopping

    1.2 Service Analysis 

         Order service, inventory service, warehousing service, points service 

    1.3 Process call

  • After the user completes the payment for an order, he will go to the order service to update the order status
  • The order service calls the inventory service to complete the corresponding functions
  • The order service calls the warehousing service to complete the corresponding functions
  • The order service calls the points service to complete the corresponding functions 

     1.4 Spring Cloud 

2. Spring Cloud Core Components 

    2.1 Eureka

  •  Eureka is the registration center in the microservice architecture, which is responsible for the registration and discovery of services.
  •  The order service wants to call the inventory service, warehousing service, or point service, how to call it?
  •  The order service doesn't even know which machine the inventory service is on! Even if he wanted to initiate a request, he didn't know who to send it to, so he was powerless!

     

Eureka Client: Responsible for registering the information of this service into Eureka Server

Eureka Server: Registry, which has a registry, which saves the machine and port number of each service 

    2.2 Feign

  • Now the order service does know where the inventory service, point service, and warehouse service are, and which port numbers it is listening to. But a new problem arises again: how to establish a network connection with other services from the order service, and then send a request there. 

 

    2.3 Ribbon 

        Cluster service: Inventory service is deployed on 5 machines

  •   192.168.169:9000
  •   192.168.170:9000
  •   192.168.171:9000
  •   192.168.172:9000
  •   192.168.173:9000 

Ribbon is designed to solve this problem. Its function is load balancing, which will help you select a machine for each request, and evenly distribute the requests to each machine 

  •  First, Ribbon will obtain the corresponding service registry from Eureka Client, and know which machines all services are deployed on and which port numbers are being listened to. 
  •  Then Ribbon can use the default Round Robin algorithm to select a machine from it
  •  Feign will construct and initiate a request for this machine.

     2.4 Hystrix 

  • In the microservice architecture, a system will have many services.
  • Take the above business scenario as an example: the order service needs to call three services in a business process.
  • Now suppose that the order service itself has at most 100 threads that can process requests. Then, the point service unfortunately hangs up. Every time the order service calls the point service, it will be stuck for a few seconds, and then a timeout exception will be thrown. 

       Something went wrong: the service avalanche problem in the microservice architecture 

  • If the system is in a high-concurrency scenario, when a large number of requests come in, all 100 threads of the order service will be stuck in the request point service. As a result, the order service does not have a thread that can process the request
  • Then it will cause others to request the order service and find that the order service is also hung up and does not respond to any requests.
  • Hystrix is ​​a framework for isolation, circuit breaking and degradation. 
  • For example, the order service requests inventory service is a thread pool, the request storage service is a thread pool, and the request credit service is a thread pool. Each thread in the thread pool is only used to request that service.

      

       2.5 Zuul

           This component is responsible for network routing. 

  • In the general microservice architecture, a gateway will inevitably be designed in it, such as android, ios, pc front end, WeChat applet, H5 and so on. You don’t need to care about hundreds of services in the backend, you know that there is a gateway, and all requests go to the gateway, and the gateway will forward the request to each service in the backend according to some characteristics in the request. After having a gateway, there are many benefits, such as unified downgrade, current limiting, authentication and authorization, security, and so on. 

              sum of components 

  •  Eureka: When each service starts, Eureka Client will register the service to Eureka Server, and Eureka Client can also pull the registry from Eureka Server in turn, so as to know where other services are
  •  Ribbon: When a request is initiated between services, load balancing is done based on Ribbon, and one of the multiple machines of a service is selected
  •  Feign: Based on Feign's dynamic proxy mechanism, according to the annotation and the selected machine, splice the request URL address and initiate the request
  •  Hystrix: The request is initiated through the thread pool of Hystrix. Different services use different thread pools, which realizes the isolation of different service calls and avoids the problem of service avalanche
  •  Zuul: If the front-end and mobile end want to call the back-end system, they enter through the Zuul gateway uniformly, and the Zuul gateway forwards the request to the corresponding service

               process 

  1. Requests are uniformly accessed through the API gateway (Zuul) to access internal services.
  2. After the gateway receives the request, it obtains available services from the registration center (Eureka) 
  3. After the load is balanced by the Ribbon, it is distributed to the specific instance of the backend
  4. Microservices communicate and process business through Feign
  5. Hystrix is ​​responsible for handling service timeout fuses

3. spring Cloud relationship 

     Spring Cloud contains many sub-projects: Netflix and Alibaba are the two most used standards

   3.1 Spring Cloud Netflix first generation 

     SDKs for various Netflix components, including Eureka, Ribbon, Feign, Hystrix, Zuul, Archaius, and more. 

  • Netflix Eureka: A service governance component based on Rest services, including the implementation of service registry, service registration and service discovery mechanism, and realizes cloud load balancing and failover of middle-tier servers.
  • Netflix Ribbon: A service invocation component for client-side load balancing.
  • Netflix Hystrix: A fault-tolerant management tool that implements the circuit breaker mode and provides stronger fault tolerance for delays and failures by controlling service nodes.
  • Netflix Feign: A declarative service invocation component based on Ribbon and Hystrix.
  • Netflix Zuul: Microservice gateway, providing dynamic routing, access filtering and other services.
  • Netflix Archaius: Configuration management API, including a series of configuration management APIs, providing functions such as dynamic typed attributes, thread-safe configuration operations, polling framework, and callback mechanism.

   3.2 Spring Cloud Alibaba Second Generation

  • Like Spring Cloud, Spring Cloud Alibaba is also a set of microservice solutions.
  • Spring Cloud Alibaba is committed to providing a one-stop solution for microservice development. This project contains the necessary components to develop distributed application microservices, so that developers can easily use these components to develop distributed application services through the Spring Cloud programming model.
  • Relying on Spring Cloud Alibaba, you only need to add some annotations and a small amount of configuration to connect Spring Cloud applications to Alibaba microservice solutions, and quickly build a distributed application system through Alibaba middleware.

    3.2.1 "Ali Open Source Components"

  • Nacos: Alibaba's open source product, a dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications.
  • Sentinel: A lightweight traffic control product for distributed service architecture, using traffic as an entry point to protect service stability from multiple dimensions such as traffic control, circuit breaker degradation, and system load protection.
  • RocketMQ: An open source distributed messaging system, based on highly available distributed cluster technology, provides low-latency, highly reliable message publishing and subscription services.
  • Dubbo: Apache Dubbo™ is a high-performance Java RPC framework for service communication.
  • Seata: Alibaba's open source product, an easy-to-use high-performance microservice distributed transaction solution.

    3.2.2 "Ali Commercialization Components"

  • Alibaba Cloud ACM: An application configuration center product that centrally manages and pushes application configurations in a distributed architecture environment.
  • Alibaba Cloud OSS: Alibaba Cloud Object Storage Service (OSS for short), is a massive, secure, low-cost, and highly reliable cloud storage service provided by Alibaba Cloud. You can store and access any type of data in any application, anytime, anywhere.
  • Alibaba Cloud SchedulerX: A distributed task scheduling product developed by the Alibaba middleware team, which provides second-level, accurate, highly reliable, and highly available scheduled (based on Cron expression) task scheduling services.
  • Alibaba Cloud SMS: SMS service covering the world, friendly, efficient, and intelligent interconnected communication capabilities, helping enterprises quickly build customer access channels. 

4. Common components of SpringCloud

  1. Spring Cloud Netflix Eureka : Service Registry.
  2. Spring Cloud Zookeeper : Service Registry.
  3. Spring Cloud Consul : Service registry and configuration management center.
  4. Spring Cloud Netflix Ribbon : client load balancing.
  5. Spring Cloud Netflix Hystrix : Service fault-tolerant protection.
  6. Spring Cloud Netflix Feign : Declarative service invocation.
  7. Spring Cloud OpenFeign (alternative to Feign) : OpenFeign is Spring Cloud's annotations that support Spring MVC on the basis of Feign, such as @RequesMapping and so on. OpenFeign's @FeignClient can parse the interface under SpringMVC's @RequestMapping annotation, and generate an implementation class through a dynamic proxy, implement load balancing and call other services in the implementation class. Spring Cloud Netflix Zuul: API gateway service, filtering, security, monitoring, current limiting, routing.
  8. Spring Cloud Gateway (alternative to Zuul) : Spring Cloud Gateway is an official Spring gateway developed based on technologies such as Spring 5.0, Spring Boot 2.0 and Project Reactor. Spring Cloud Gateway aims to provide a simple and effective unified API for microservice architecture Routing management method. As the gateway in the Spring Cloud ecosystem, Spring Cloud Gateway aims to replace Netflix Zuul. It not only provides a unified routing method, but also provides basic functions of the gateway based on the Filter chain, such as: security, monitoring/burying, and limiting flow etc.
  9. Spring Cloud Security : Security authentication.
  10. Spring Cloud Config : Distributed configuration center. Configuration management tool, supports the use of Git to store configuration content, supports external storage of application configuration, supports client configuration information refresh, encryption and decryption of configuration content, etc.
  11. Spring Cloud Bus : event, message bus, used to propagate state changes in the cluster (for example, configuration change events), and can be combined with Spring Cloud Config to realize hot deployment.
  12. Spring Cloud Stream : Message-driven microservices.
  13. Spring Cloud Sleuth : Distributed service tracing.
  14. Spring Cloud Alibaba Nacos : Alibaba's open source product, a dynamic service discovery, configuration management and service management platform that makes it easier to build cloud-native applications.
  15. Spring Cloud Alibaba Sentinel : A lightweight traffic control product for distributed service architecture, using traffic as an entry point to protect service stability from multiple dimensions such as traffic control, circuit breaker degradation, and system load protection.
  16. Spring Cloud Alibaba RocketMQ : An open source distributed messaging system, based on highly available distributed cluster technology, provides low-latency, highly reliable message publishing and subscription services.
  17. Spring Cloud Alibaba Dubbo : Apache Dubbo™ is a high-performance Java RPC framework for service communication.
  18. Spring Cloud Alibaba Seata : Alibaba open source product, an easy-to-use high-performance microservice distributed transaction solution.

5. Version relationship

    Spring Boot

    Spring Cloud

    Spring Cloud Dependencies

    Spring Cloud Chinese Study Guide

    Spring Cloud Alibaba

6. Version management specification

7. Nacos build

    Nacos official website

Nacos single node, that is, the standalone mode, uses an embedded database to store data by default, which is inconvenient to observe the basic situation of data storage. After version 0.7, the ability to support MySQL data sources has been added. When building a cluster, it is necessary to connect Nacos to Mysql for data storage.

If you want to build a highly available cluster environment, at least the following conditions must be met:

JDK 1.8+;

Maven 3.2.x+;

MySQL 5.6.5+ (it is recommended to use at least active/standby mode for production use, or use a high-availability database);

3 or more Nacos nodes can form a cluster; 

   7.1 Configure Nacos database source 

  • Enter the Mysql database and run the Sql file under the conf folder under the downloaded Nacos file

 

# db mysql
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=1234

   7.2 Start Nacos and visit the Nacos management page

  • Login account nacos
  • login password nacos 

 

 8. Consumer and producer writing

     8.1 Create a new maven project as the parent project  

  • Note! Delete the src directory in the parent project. The parent project does not write code and is only responsible for providing dependencies for sub-projects. 

       8.1.1 Modify the parent project pom file and add the following code

<?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.jmh</groupId>
  <artifactId>springcloud01</artifactId>
  <version>1.0-SNAPSHOT</version>
  <!--pom代表这个是个父工程-->
  <packaging>pom</packaging>

  <!--指向儿子-->
  <modules>
    <module>nacos_provider</module>
    <module>nacos_consumer</module>
  </modules>

  <name>springcloud01 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <!--提供版本-->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring-boot.version>2.4.1</spring-boot.version>
    <spring-cloud.version>2020.0.0</spring-cloud.version>
    <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
  </properties>

  <!--提供依赖-->
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
  </dependencies>

  <!--提供依赖版本-->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring-boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alibaba-dependencies</artifactId>
        <version>${spring-cloud-alibaba.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>


</project>

packing : (packaging type, default is jar)

pom : parent project (there is no java code in the pom project, and no code is executed, just for aggregation projects or transitive dependencies)

jar : internal calls or used as services

war : the project that needs to be deployed

DependencyManagement : (Manage the version of the jar package, let the subproject refer to a dependency without displaying the listed version number) The difference between dependencyManagement and dependencies : even if the dependencies do not write the dependency in the subproject, the subproject will still be from the parent project Inherit this dependency (inherit all)

DependencyManagement only declares dependencies, but does not implement imports, so sub-projects need to display the dependencies that need to be declared. If the dependency is not declared in the subproject, it will not be inherited from the parent project. Only when the dependency is written in the sub-project and no specific version is specified, the item will be inherited from the parent project, and both version and scope are read from the parent pom. In addition, if the version number is specified in the subproject, the jar version specified in the subproject will be used. modules (used to manage modules in the same project)

Reasons to import three versions:

 nacos comes from Spring Cloud Alibaba (used to replace SpringCloud Eureka and SpringCloud Config), feign comes from Spring Cloud, and other normal ones come from SpringBoot 

  8.2 Create a new springboot project as a subproject (producer builds Provider)

     8.2.1 Modify and add subproject pom files  

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jmh</groupId>
    <artifactId>nacos_provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos_provider</name>
    <description>Demo project for Spring Boot</description>

    <!--指向父亲-->
    <parent>
        <artifactId>springcloud01</artifactId>
        <groupId>com.jmh</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>


    <dependencies>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

      8.2.2 Modify and add sub-project application.yml file

server:
  port: 8081
spring:
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
  application:
    name: nacos-provider

     8.2.3 Modify and add subproject startup class

package com.jmh.nacos_provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderApplication {

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

}

 8.3 Create a new springboot project as a subproject   (consumer builds Consumer)

     8.3.1 Modify and add sub-project pom files

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jmh</groupId>
    <artifactId>nacos_consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos_consumer</name>
    <description>Demo project for Spring Boot</description>

    <!--指向父亲-->
    <parent>
        <artifactId>springcloud01</artifactId>
        <groupId>com.jmh</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

       8.3.2 Modify and add sub-project application.yml file

server:
  port: 8082
spring:
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
  application:
    name: nacos-consumer

       8.3.3 Modify and add subproject startup class

package com.jmh.nacos_consumer;

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

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {

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


}

9. Start the sub-project Tomcat server and go to the Nacos management page to view the service

  • Start the subproject Tomcat server 

  •  Go to the Nacos management page to view services

 10. Call method

  • For example, we consumers want to ask the producer for a chicken leg! Then how do we communicate between two unrelated modules? Next, let’s look at the editor’s operation and directly upload the code 

     10.1 New sub-project [producer build Provider] Controller module code 

package com.jmh.nacos_provider.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 蒋明辉
 * @data 2022/11/2 22:13
 */
@RestController
public class ProviderController {

    @RequestMapping("/run")
    public String run(){
        //生产鸡腿
        return "鸡腿";
    }
}

     10.2 Modify and add sub-project [consumer build Consumer] pom file

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

ribbon status: stop updating

Alternative: Spring Cloud Loadbalancer 

     10.3 New sub-project [consumer build Consumer] Controller module code 

package com.jmh.nacos_consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 蒋明辉
 * @data 2022/11/2 22:14
 */
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/run")
    public String run(){
        //问生产者要鸡腿
        String forObject = restTemplate.
                getForObject("http://nacos-provider/run", String.class);
        return forObject;
    }

}

     10.4 Modify and add sub-project [consumer build Consumer] startup class

package com.jmh.nacos_consumer;

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

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {

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

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

       10.5 Start subproject server call and test method

Guess you like

Origin blog.csdn.net/m0_63300795/article/details/127662046#comments_27119909