SpringCloud Alibaba goes from beginner to master

I. Course introduction

1.1 Course guidance

  • What is a SpringCloudAlibaba?

    • Alibaba combined with its own micro service practice, open source micro service bucket
    • Incubated in a Spring Cloud project, it is likely to become the implementation of the Spring Cloud second generation standard
    • Widely used in the industry, there have been many successful cases
  • Real application scenario of Spring Cloud Alibaba

    • Large complex systems, such as large e-commerce systems
    • High concurrency systems, such as large portals, SEC kill systems
    • Systems with unclear requirements that change rapidly, such as startup business systems
  • Spring Cloud Alibaba and Spring Cloud

    • Simply put, SpringCloud Alibaba is a sub-project of SpringCloud, which is the implementation of the second generation of SpringCloud.
    • The illustration is as follows:
    • To sum up:
      • Component performance is stronger
      • Good visual interface
      • Simple setup and low learning curve
      • The documentation is rich and in Chinese
  • What can you learn from reading this blog?

    • Usage and implementation principle of SpringCloud Alibaba core components
    • SpringCloud Alibaba combines wechat mini program to learn the use of real development from “0”
    • How to avoid stepping on pits in actual work, the correct way to think about problems
    • SpringCloud Alibaba advancements: code optimization and improvement, microservice monitoring
  • What will the course cover in advance?

  • Course Ideas:

    1. Analyze and disassemble microservices
    2. Write the code
    3. Analyze existing architecture issues
    4. Introduce microservice components
    5. Optimize the refactoring
  • Important components of SpringCloud Alibaba are summarized as shown in the figure:

1.2 Construction of project environment

  • Software for the class

    • JDK8
    • MySQL
    • Maven installation and configuration
    • IDEA and some shortcut keys
  • Install Maven:

    • We can use Maven with IDEA, or download and install Maven by ourselves
  • Install JDK and MySQL

    • We can install it by searching relevant tutorials on the Internet

SpringBoot foundation

2.1 Overview of this Chapter

2.2 What is Spring Boot? What can be done?

  • What is?
    • SpringBoot is a scaffolding for rapid development
  • Role?
    • Quickly create standalone, production-grade opportunity Spring applications
  • Feature?
    • You do not need to deploy a WAR file
    • Provides the starter simplified configuration
    • Automatically configure Spring and third-party libraries whenever possible
    • Provides production-ready functions, such as metrics, health checks, external configuration, and so on
    • No code generation & no XML

2.3 Writing the first SpringBoot application

  • Requirements:
    • Integration of Spring MVC
    • /test path, we become “endpoint”
  • Use Spring Initializr to quickly create a SpringBoot application
    • Click Create New Project -> Spring Initializr -> Configure JDK-> Select Default-> Next, as shown:

    • Configure the Group and Artifact based on your actual situation, select Maven for Type (or Gradle for Gradle project), and configure other items based on your actual situation, as shown in the figure below:

    • Select the required dependencies and SpringBoot version, as shown in the figure, except for 2.1.5, the upper version is not official, so we select version 2.1.5, as shown in the figure:

We can deploy a Costom by ourselves, combined with official documents and online articles, when the environment is internal king, we can deploy a Costom by ourselves, as shown in the figure:

! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e82b5ebb18414b448932f48cfdcb729a~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code
  • Create the interface and start the access, as shown:

By starting the startup class, we can run the project directly, we don’t need to type the WAR package and put it in Tomcat;

2.4 Analysis of Spring Boot Application Composition

  • Rely on:
  • Comments:
  • Configuration:
  • Static files:
    • The resource/static directory
  • Template engine:
    • Support: Freemarker, Groovy, Thymeleaf, Mustache
    • There is less use for template engines now that the front and back ends are being developed separately
    • The resource/templates directory

2.5 SpringBoot development three axe

  • Add dependencies (integrate what, add what dependencies)
    • The official starter format is spring-boot-starter- XXX
    • The unofficial starter format is xxX-spring-boot-starter
  • Writing comments:
    • If you need an annotation, you need to add it to the startup class or to the specified location
  • Write the configuration:
    • It can be a configuration class of type Bean
    • It can also be configured under resource with yml&Properties & etc

2.6 Spring Boot Actuator Must be Configured

  • What is?
  • How to integrate?
    • Add depends on:
      	<dependency>
      		<groupId>org.springframework.boot</groupId>
      		<artifactId>spring-boot-starter-actuator</artifactId>
      	</dependency>
      Copy the code
    • Direct boot, access: IP: port /actuator
      • Health: Health check
        • We configure in application.yml to make the health check more detailed:
          	management.endpoint.health.show-details=always
          Copy the code
        • As shown in the figure:
        • The status value:
          • UP: normal
          • DOWN: There is a problem
          • OUT_OF_SERVICE: The resource is not in use or should not be used
          • UNKNOWN: I don’t know
      • Info: is not used for monitoring. It is generally used to describe applications. It is written in key-value format, as shown in the figure:
        • The display content is shown as follows:
  • The provided monitoring endpoints are shown in figure (the ones listed here are commonly used and can be viewed in the official documentation) :
  • Activate all Acttuator endpoints and add to application.yml:
  • Activate the specified endpoint:
    	management.endpoints.web.exposure.include=metrics,health
    Copy the code

    Separate multiple entries with commas

2.7 Spring Boot configuration management is mandatory

  • Supported configuration formats:
    • application.yml
    • application.yaml
    • application.properties

    Yml > YAML >properties execution order. If there are duplicate contents, properties is the final result

  • Environment variables:
    • Mark the variable name with the form ${XXX}, and add the Environment variable to the Environment variables in IDEA, as shown in the figure:
  • External configuration file
    • Spring-boot can read external configuration files and put them in the same path. The external configuration files have a higher priority, as shown in the following figure:
  • Command line arguments:
    • On the command line:
      java -jar xxx.jar --server.port=8081
      Copy the code
    • The IDEA of:

2.8 will the Profile

  • How to implement different configurations in different environments?
    • A:
      • The configuration is shown as follows:
      • Specify the environment to boot in IDEA:
      • When no environment configuration is specified, only the common part of the configuration is performed. We can configure the default environment configuration scheme, as shown in the figure below:
    • Method 2:
      • We can also create multiple profile profiles and select the specified profile during configuration, as shown in the following figure:

2.9 Summary of this chapter

  1. Use Spring Initialize to quickly create applications
  2. Application composition analysis
  3. SanBanFu
  4. Actuator
  5. Configuration management
  6. Profile

Third, the separation and writing of microservices

3.1 Overview of this Chapter

3.2 Single Application

  • What is a monolithic architecture?
    • An archive package (such as a War package) that contains all the functional applications is often referred to as a singleton application. The methodology of monomer application is monomer application architecture
  • Advantages of a single architecture
    • Architecture is simple
    • Easy to develop, test and deploy
  • Disadvantages of single architecture:
    • Complexity is high
    • The deployment is slow and the frequency is low
    • Limited scalability (e.g., I/O operation is too much, and CPU operation is too much, can’t use everything)
    • Impeding technology innovation (inconvenient to change technology stack)

3.3 the service

  • Microservice definition

    • The microservice architecture style is a way of developing a single application into a set of small services, each running in its own process and communicating between services using a lightweight communication mechanism (usually using HTTP resource apis). These services are built around business capabilities and can be deployed independently through automated and deployment mechanisms. These services share a minimal centralized management, services can be developed in different languages, using different data storage technologies;
  • Features of microservices:

    • Each microservice can run independently in its own process
    • A series of independent microservices build the system together
    • Each service is an independent business development, and a microservice focuses on a specific function, such as order management, user management, and so on
    • Use of different languages and storage technologies (project and team strength)
    • Microservices communicate with each other through lightweight communication mechanisms, such as calls through REST apis;
    • Fully automated deployment mechanism
  • Microservices Architecture Diagram:

  • Advantages of microservices:

    • Individual services are easier to develop and maintain
    • A single microservice starts quickly
    • Local changes are easy to deploy
    • The technology stack is not limited
    • On-demand scaling
  • Disadvantages of microservices:

    • Operation and maintenance requirements are high
    • The inherent complexity of distribution
    • Duplication of effort
  • Application scenarios of microservices

    • Large, complex projects
    • High service pressure
    • Services that change faster
  • Scenarios where microservices are not applicable

    • Business is stable
    • Long iteration period

3.4 Project effect demonstration

XXX

3.5 Splitting microservices

  • Domain Driven Design
  • Object orientation (by name./ by berb.) is split by noun or verb
    • Responsibility division
    • Generality division
  • Suitable particle size
    • Meet the business well
    • happiness
    • The incremental iteration
    • Continued evolution

3.6 Project architecture diagram

3.7 Database Design

  • Modeling, as shown in the figure:
  • It is then exported to create an actual MySQL table

3.8 the API documentation

  • Write Api documentation, defining in advance what functional requirements to write
  • As shown in the figure:

3.9 How Do I Create a Mini Program

  • Register your account: https//mp.weixin.qq.com
  • Fill in the information and apply to create a small program
  • Click the jump link in the activation mailbox to complete the information shown in the picture:
  • Enter the home page of the small program, we can configure the information of the small program, etc. Here we click ** development Settings **, check the AppId and AppSecret

3.10 How to use the preceding code

  • Installation Node. Js
    • To nodejs.org/en/download… Download the node. Js
    • Installation instructions:
      • The Windows operating system, the reference: jingyan.baidu.com/article/482…
      • Cenots system, reference: www.cnblogs.com/baby123/p/6…
      • MacOS operating system, use PKG directly drag to install
      • Other systems, Baidu NodeJS {operating system name} installation.
  • Assume that the corresponding NodeJS front-end project already exists
    • Package command:
      npm install
      Copy the code
    • Package acceleration command:
      npm --registry https://registry.npm.taobao.org install
      Copy the code
    • The development environment starts deployment:
      npm run dev
      Copy the code
    • Production environment construction:
      npm run build
      Copy the code
  • Download & Install wechat Developer tools:
    • To: developers.weixin.qq.com/miniprogram… Download developer tools
    • Installing developer Tools

3.11 Creating An Item -1

  • Technical selection:
    • Spring Boot(Rapid development)
    • Spring Mvc (Mvc Framework)
    • Mybatis(Persistence layer framework, operational database)+ universal Mapper
    • Spring Cloud Alibaba(Distributed)
  • Project structure planning:

3.12 Creating Project 2

  • Introduce a universal Mapper for the project
    1. Remove original dependencies (if present)
      	<dependency>
      		<groupId>org.mybatis.spring.boot</groupId>
      		<artifactId>mybatis-spring-boot-starter</artifactId>
      	</dependency>
      Copy the code
    2. Switch to a generic mapper
      	<dependency>
      		<groupId>tk.mybatis</groupId>
      		<artifactId>mapper-spring-boot-starter</artifactId>
      		<version>2.1. 5</version>
      	</dependency>
      Copy the code
    3. Use the MapperScan annotation on the startup class to scan for the required interface
      @MapperScan("xxx")
      Copy the code

      As shown in the figure:

    4. Application. Yml configures mysql information

      The Model generated by general Mapper special code generator will add @table, @ID, @column annotations on the original basis to facilitate automatic mapping back to the database field. There are several ways to run MBG, and here are just two of the more common ones. And the content will be configured for this mode of operation;

    5. Run MBG with Java encoding:
      • Include this example in the Generatr project test code:
        https://github.com/abel533/Mapper/blob/master/generator/src/test/java/tk/mybatis/mapper/generator/Generator.java
        Copy the code

      To use this approach, MBG dependencies need to be introduced, and there should already be universal Mapper dependencies in the project.

    6. Use Plugin to run:
      1. Introduce the code shown in the following figure to the corresponding location in pom.xml:

        Maven-compiler-plgin is provided in SpringBoot, so we don’t need to add it

      2. inresources/generatorCreate the Generatorconfig.xml file under the generatorConfig.xml directory, as shown in the following figure:

      3. You can go to baidu under the content of the file, the corresponding placeholder information can be filled

      4. If there is an external reference to config.properties, we need to create a separate reference and add the imported information such as username and password to the config.properties, as shown in the figure below:

      5. After filling in and configuring everything in GeneratorConifg.xml, click on Maven’s plugin: Mybaits-Generator on the right and select Generate, as shown:

      6. It can generate both model and general-purpose Maper code, as shown below:

3.13 Lombok integration simplifies code writing

  • Lombok
    • Function: simplify code writing and improve development efficiency

    • Project homepage :(www.prjectlombok.org/)[https://w…

    • IDEA integration Lombok:

    • After installing the plugin in IDEA, introduce the following dependencies (you can also use the latest version of Baidu)

      <dependency>
      	<groupId>org.projectlombok</groupId>
      	<artifactId>lombok</artifactId>
      	<version>1.188.</version>
      	<scope>provided</scope>
      </dependency>
      Copy the code
    • @getter, @setter, @toString, @equalSandHashCode can automatically generate getters, setters, ToString and other methods, as shown in the figure below:

    • Notes:

      • Using @data is equivalent to using these annotations, which are internally aggregated;
      • RequiredArgsConstructor generates a constructor for a property marked as final;
      • @Builder uses the Builder mode, which can create objects and assign values at the same time.
      • @sl4j annotation, you can use the log function directly
    • Stability function and laboratory function, specific functions can be viewed on the official website and examples;

    • Lombok and code Generators:

      • When Lombok adds model code generation, it directly generates Lombok’s @Getter@Setter@ToString@Accessors(chain=true) four-class annotations
      • The user adds the corresponding Model class with annotations to the plug-in configuration item

3.14 Resolve the red warning of IDEA

  • When we introduced Mapper, we exposed warnings like this:

    You can see a red warning under userMapper. While the code itself is fine and works, it’s always a little gross to have a warning. This paper analyzes the causes and lists the centralized solutions to the warning.

  • The reason:
    • IDEA is known to be smart enough to understand Spring’s context. However, UserMapper interface is Mybatis, IDEA can not understand.
    • while@AutowiredDependency objects are required by default (i.euserMapper) must exist. IDEA thinks that the instance/proxy of the injected object is null, so it gives a friendly hint.
  • Solution:
    • Method 1: Set the @AutoWired annotation to Required = false and allow null values without warning. As shown in the figure:
    • Method two: use@Resourcereplace@Autowired
    • Method 3: Annotate the Mapper interface with @repository
    • Method 4: Use Lombok annotations and constructor injection.
      • Use this annotation directly on the class:
        @RequiredArgsConstructor()
        Copy the code
      • You can also use this method, more recommended:
        @RequiredArgsConstructor(onConstructor = @__(@Autowired))
        Copy the code
      • As shown in the figure:
      • Conclusion: This method is most recommended for two reasons:
        1. Spring does not recommend using the @autowired annotation directly on a class field, for reasons described in Why Field Injection is Evil. This method can be used to inject field into programming constructs.
        2. Demonstrates Lombok’s strengths and simplifies your code. And you don’t have to annotate every field with @Autowired.

      The downside of this approach is that if you have complex dependencies between classes, especially if you have circular dependencies (A to B, B to A, or indirect references), the references will not start… This is actually the downside of constructor injection;

    • Method 5: Turn off the IDEA warning
    • Method 6: Install Mybatis Plugin (as shown in the figure)

3.18 Problems existing in the existing architecture

  • What if the address changes?
  • How to achieve load balancing?
  • What if the user center is down?

Iv. Introduction to Spring Cloud Alibaba

4.1 What is Spring Cloud Alibaba

  • A set of tools for quickly building distributed systems (the main features are shown in figure)
  • Some sub-projects are shown as follows:
  • Commonly used subprojects are shown as follows:
  • What is a SpringCloudAlibaba?
    • It is a subproject of Spring Cloud
    • Dedicated to providing one-stop solutions for micro-service development
      • Contains the necessary components for microservice development
      • Opportunity Spring Cloud complies with Spring Cloud standards
      • Ali’s micro service solution
    • SpringCloud Alibaba
    • After our arrangement, the picture is as follows:

4.2 Version and Compatibility

  • Our usual version is semantic version control. The version number in version describes the general situation of this version, as shown in the figure:
  • Many of SpringCloud’s projects are named alphabetically because it can easily confuse the version numbers of some of its child dependencies, so it doesn’t use numbers at all.
  • Version 4:
  • The SpringCloud release lifecycle
    • Release schedule :(github.com/spring-clou…
    • Release records :(github.com/spring-clou…
    • Release termination statement :(spring. IO /projects/sp…
  • Version Compatibility:
  • Future version compatibility (if SpringCloudAlibaba enters the second generation)

  • How to select version in production environment?
    • Never use unstable /end-of-life versions
    • Try to use the latest generation
      • XXX.RELEASE hold on
      • SR2 is generally available on a large scale after that

4.3 Integrate SpringCloudAlibaba for the project

  • Integrated SpringCloudAlibaba
    • Integrated SpringCloud
      • Importing dependencies, as shown:
    • Integrated SpringCloudAlibaba
      • If the Greenwich version is used, the following dependencies are used:
      • If you are using the Finchley version, use the following dependency:
    • The first way to integrate Cloud and Alibaba is as shown in the figure below:

Using what is shown, we can import other components in the Cloud without specifying a version, and it will automatically configure the corresponding version. If the content in the figure is not used, it may lead to dependency conflict and dependency inconsistency.

Service discovery -Nacos

5.1 Service providers and service consumers

  • Service provider: the called party of a service (that is, a microservice that provides an interface to other microservices)
  • Service consumer: callers of services (i.e., microservices that invoke other microservice interfaces)

5.2 Analyzing service discovery principles in plain English

  • Question: What if the user address changes?
    • Service discovery mechanism is to record IP address, service name, heartbeat and other data of service provider through a middleware (for example, mysql is used to store these information), and then service consumers will go to this intermediate platform to query relevant information, and then access the corresponding address, which is service registration and service discovery.
    • When the user address changes, there is no impact, because the service provider has modified the user address, which will be updated in the middleware. When the service consumer accesses the middleware, it can obtain the latest user address in time, so that the service cannot be found due to the change of the user address

5.3 What is Nacos?

  • IO/zh-CN /docs/ what-IS-nacos.html)[]
  • Microservices Panoramic Architecture Diagram:
  • Architecture evolution diagram after the introduction of Nacos:

5.4 Setting up the Nacos Server

  • Download Nacos Server
    • (Download address)[github.com/alibaba/nac…]
  • Build Nacos Server
    • IO /zh-cn/docs/…
  • Start the server:
    • Linux/Unix/Mac:
      sh startup.sh -m standalone
      Copy the code
    • Windows:
      cmd startup.md
      Copy the code

    The startup command is in single-machine mode, not cluster mode

5.5 Registering applications with Nacos

  • Goal:
    • User centers register with Nacos
    • Content centers are registered with Nacos
    • Testing: The content center always finds the user center
  • User centers register with Nacos
    • Add depends on:
      	<dependency>
      		<groupId>org.springframework.cloud</groupId>
      		<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
      	</dependency>
      Copy the code

      The dependency rules in SpringCloud are similar to SpringBoot. Spring-cloud-starter -{name of spring Cloud sub-project}-{module name}, for example, feign can be spring-cloud-starter- OpenFeign, and sentinel can be like this: Spring-cloud-starter-alibaba-sentinel, when there are no modules, there is no need to add modules, such as Feign

    • Annotations:
      • The @enableDiscoveryClient annotation was previously required on the startup class, but is now unnecessary
    • Add the configuration:
      	spring:
      		cloud:
      			discovery:
      				server-addr: localhost:8848Use - instead of _ to specify the nacos server addressCopy the code

5.6 Introduce service discovery for the content center

  • Refer to Section 5.5 for the introduction of the content center, as well as other services, and change the service name accordingly;
  • The successful registration is shown as follows:

Some information about microservices provided by Nacos can be obtained in the code by using relevant Api of DiscoverClient. The invocation method is shown in the figure below:

! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f701b2756963448cb9ea4663c70e0ec2~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code

5.7 Domain model of Nacos service discovery

  • As shown in the figure:
  • Different namespaces are isolated. Groups can be used to manage namespaces (for example, multiple rooms with multiple services can be divided into one Group for services in the same room). If a Cluster is in the same Cluster, its own Cluster service will be invoked as far as possible.
  • The definitions of each keyword are as follows:
    • Namespace: Implements isolation and defaults to public
    • Group: Different services can be grouped into a Group. Default is DEFAULT_GROUP
    • Service: micro Service
    • Cluster: a virtual partition for a specific microservice, DEFAULT
    • Instance: indicates a microservice Instance
  • Specify method, code as shown in figure:
    • First configure NameSpace in Nacos:
    • Then add fields to the code:

5.8 Nacos metadata

  • What is metadata? (Metadata)
    • Nacos data (such as configuration and service) description information, such as service version, weight, DISASTER recovery policy, load balancing policy, authentication configuration, and various customized labels. From the perspective of scope, Nacos data can be classified into service-level meta information, cluster meta information, and instance meta information.
  • Application
    • Attributes that identify the service of the service provider
  • Service Group
    • Different services can be grouped into the same group
  • Virtual Cluster
    • All service instances of a service form a default cluster. The cluster can be further divided according to requirements. The unit can be virtual cluster.

  • What is metadata?
    • Nacos. IO /zh-cn/docs/…
    • Level: [Service level, Cluster level, Instance level]
  • Metadata functions:
    • Provide description information
    • Make microservice invocation more flexible: for example, microservice versioning
  • Metadata operation mode:
    1. As shown in the figure above, you can control metadata at the cluster, service, and instance levels in Nacos Server
    2. Configure in application.yml, as shown in the figure below:

Implement load balancing

6.1 Two Load Balancing Modes

  • Server side load balancing:
  • Client load balancing:

6.2 Creating a Client-side load balancer

  • Part of the handwritten load balancer code is shown in the figure below:

    The main principle of a handwritten load balancer is to obtain all urls of the service, and then invoke the specified URL in polling or random mode

6.3 Using the Ribbon to Implement Load Balancing

  • What is the Ribbon?
    • The Ribbon provides rich load balancing algorithms.
  • The introduction of Ribbon:
    1. Add dependencies: This step is omitted because Nacos is already integrated with the Ribbon
    2. Writing comments:
      • Add @loadBalanced to the RestTemplate Bean as shown:
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate{
        	return new RestTemplate()
        }
        Copy the code

      • Use RestTemplate:

6.4 Ribbon of

  • The Ribbon is shown in the figure below. If it doesn’t fit, you can rewrite it

6.5 Load Balancing Rules built in the Ribbon

  • Load balancing rules are shown as follows:

6.6 Fine-grained Configuration Customization 01-Java code

  • Configure in Java code
    • Create under the and startup class package:
      	@ RibonClient (name = "service name", the configuration = RibbonConfiguration. Class)
      	public class XXXRibbonConfiguration{}Copy the code
    • As shown in the figure:
    • Create in a different path from the startup class package:
      	@Configuration
      	public class RibbonConfiguration{
      		@Bean
      		public IRule ribbonRule(a){
      			/ / random
      			return newRandomRule(); }}Copy the code
    • As shown in the figure:

    The boot class in the Ribbon cannot be scanned by the boot class. Otherwise, parent and child contexts may overlap, causing various bug problems.

6.7 Fine-grained Configuration Customization 02- Parent and child Context

  • As shown in the official description, overlapping parent and child contexts become global sharing, and all services are configured in this way;

6.8 Fine-grained Configuration Customization 03- Configuring Attributes

  • Add the configuration to application.yml in the resource directory:
    XXX service name: ribbon: NFLoadBalancerRuleClassName: com.net flix. Loadbalancer. # RandomRule wants to rule the class of the full pathCopy the code
  • As shown in the figure:

6.9 Fine-grained Configuration Customization 04- Two methods

  • The comparison is shown in the figure below:

Attribute configuration mode has a higher priority.

6.10 Fine-grained Configuration Customization 05- Best Practices

  1. Try to use attribute configuration, attribute mode can not be implemented in the case of code configuration
  2. In the same microservice, try to keep the uniformity, such as unified use of attribute configuration, do not mix the two ways, increase the complexity of positioning code;

6.11 Global Configuration

  • Overlapping parent and child contexts (strongly not recommended, as it may cause the project to fail and is not a scientific solution)
  • In the XXXRibbonConfiguration we defined, change the configuration to defaultConfiguration, as shown in the figure:

6.12 Supported Configuration Items

  • Each of these is supported by defining a Bean that returns its implementation class. If the implementation class is configured, the specified key value and value value are the full path address of the implementation class.
  • The configuration rules are as follows:
  • The code configuration is shown below:
  • The configuration mode is as follows:

The code configuration and property configuration are the same as the previous custom configuration above;

6.13 Hunger loading

  • When using RestTemplate, Rabbon is lazy loading and the first access is slow. We can change the loading mode from lazy to hungry so that the first request is not slowapplication.ymlTo configure:
    	ribbon:
    		eager-load
    			enabled: trueClients: XXX Service name # Multiple services separated by ', 'Copy the code

Here is to turn on hunger loading

6.14 Extension Ribbon- Support Nacos weights

  • Because the Spring subproject does not define a specification for weights, it does not support weights, whereas Nacos does;
  • Extend the Ribbon to support the weight of three ways: hppts://www.imooc.com/article/288…
  • Operation as shown in figure:
    • Define a class to inherit from another classAbstractLoadBalancerRuleAnd the implementation method, as shown in the figure:
    • Completion code:
    • Define the Bean to replace the default:
    • Edit weights in Nacos:

6.15 Extension Ribbon- The same cluster is called first

  • Domain model for service discovery:
  • Using Cluster can be very convenient to achieve a unified Cluster priority call method, specific can be Baidu

6.16 Extension Ribbon- The metadata-based version

  • We can extend the Ribbon to use Nacos metadata to solve this problem.
  • Metadata solution, document jump: Using metadata to solve data coexistence problems

6.17 Understanding NameSpace of Nacos in Depth

  • A NameSpace is a NameSpace. Services in different namespaces are isolated from each other. This allows multiple environments to register Nacos at the same time, distinguishing dev/test/prod from other environments by being in different namespaces
  • The code is shown below:

6.18 Problems with the existing architecture

  • The remote call code is unreadable, the URL is too long to accurately distinguish services, and complex urls are difficult to maintain
  • Microservices are adapted to rapid iteration and, for now, are difficult to respond to changing requirements
  • Different programming experiences

Declarative HTTP client: Feign

7.1 Implementing remote Http Calls using Feign

  • Feign is a declarative remote call HTTP client for NetFlix;
  • Making the address
  • Integration methods:
    1. Introduce dependencies in POM.xml
      <dependency>
      	<groupId>org.springframework.cloud</groupId>
      	<artifactId>spring-cloud-starter-openfeign</artifactId>
      </dependency>
      Copy the code
    2. Write comments and add them to the bootstrap class@EnableFeignClientsannotations
    3. Write configuration, not yet
    4. Write a Feign example:
      @feignClient (name=" XXX service name ")
      public interface xxxFeignCLient{
      	/** * This is a Feign lovelorn ** /@GetMapping("xxx/xxx")
      	XXX findById(xxx xxx)
      }
      Copy the code

      Something like this:

      ! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/647844a722674c71ab02213e6e81afcf~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code
  • Feign and the Ribbon can also be integrated together. Please refer to Feign’s integration method

7.2 Feign Composition

  • The composition is shown in the figure:

    RequestInterceptor can be used to intercept, we can add general logic, such as for each Feign method when called, add Header, Header can be unified with AuthToken

7.3 Fine-grained Configuration Customization -01-Java code

  • Feign log level:

    Feign’s log level is different from the general log level, and it defines four log levels of its own

  • The Java code configuration is shown below:

In the Configuration class, @Configuration cannot be added. If it is added, it must be outside of the place that the launcher class can scan, otherwise a parent-child context exception will occur and the Configuration class will be shared globally

7.4 Fine-grained Configuration Customization -02- Configuring Attributes

  • In resource/appilcation. Yml:
    Feign: client: config: # Name of the microservice you want to call user-center: loggerLevel: fullCopy the code

7.5 Global Configuration -01 using Java code

  1. Overlapping parent and child contexts (not recommended; this is done in an informal manner)
  2. The only correct approach: @enableFeignClients (defaultConfiguration= XXX.class) in the startup class

7.6 Global Configuration -02- Attribute Configuration Mode

  • Set it in resource/application.yml

7.7 Supported Configuration Items

  • Code mode, as shown in the figure:

  • Attribute mode, as shown in the figure:

7.8 Configuration Best practices

  • Summary:
    • Rinnbon configuration vs Feign configuration
    • Feign code vs. attribute
    • Summary of best Practices
  • The comparison diagram is as follows:
  • Feign code vs. attribute:
  • Best practices:
    • Try to use attribute configuration, attribute mode can not be implemented in the case of code configuration
    • Try to keep things as simple as possible within the same microservice, such as using property configuration as a whole, rather than mixing the two

7.9 Feign Inheritance

  • When we have some services that have the same Feign remote calls, we can isolate the common Feign and write it in some external place and reference it, directly inheriting it. In this way, it can be amended once, effective everywhere, and written in accordance with the contract.
  • This is not officially recommended because it leads to tight coupling of multiple microservices. In fact, many companies are using this approach, and individuals can weigh the pros and cons.

7.10 How do GetMapping Send Feign Requests

  • Feign calls with @getMapping requests will still send Post requests, so the request will be abnormal.
  • The solutions are as follows:
    1. Use the @SpringQueryMap recommendation, as shown:
      @FeignClient("xxxx-xx")
      public interface UserFeignClient{
      	@GetMapping("/get")
      	public User get0(@SpringQueryMap User user);
      }
      Copy the code
    2. Method two: The Url has several parameters, Feign interface methods have several parameters. What are the parameters to specify the request using the @requestParam annotation
      @FeignClient("xxxx-xx")
      public interface UserFeignClient{
      	@GetMapping("/get")
      	public User get0(@RequestParam("id")Long id,@RequestParam("username")String str);
      }
      Copy the code
    3. Multi-parameter urls can also be built using a Map. This simplifies Feign interface writing when the target Url parameters are very large:
      @FeignClient("xxxx-xx")
      public interface UserFeignClient{
      	@GetMapping("/get")
      	public User get0(@RequestParam Map<String,Object>map);
      }
      Copy the code

      The call can be made with code similar to the following:

7.11 Feign used without the Ribbon

  • The Ribbon does not directly specify the service name to invoke, but instead uses the URL:
  • The code looks like this:
  • Feign supports placeholders, as shown below:

In earlier Spring Cloud releases, there was no need to provide the name attribute. Starting with Brixton, @FeignClient must provide the Name attribute or the application will not start properly.

7.12 RestTemplate VS Feign

  • The comparison is shown below:

  • How to choose?

    • Rule: Use Feign instead of RestTemplate
    • If Feign can’t solve it, only RestTemplate can

7.13 Feign Common Performance Optimization

  • Configuring connection pooling (15% increase)

    • OkHtpp HttpClient all support connection pooling
  • HttpClient configuration:

    1. Introducing dependencies:
      	<dependency>
      		<group>io.github.openfeign</groupId>
      		<artifactId>feign-httpclient</artifactId>
      	</dependency>
      Copy the code
    2. Application. Yml
      Feign: client: config: # Global configurationdefault# let Feign use Apache HttpClient for requests instead of the default urlHttp enabled:true# feign maximum number of connections max-connections200# feign maximum number of connections per path max-connections-per-route:50
      Copy the code

      As shown in the figure:

      ! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ed7cb5279c2a46fc86a3d0672a296c89~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code
  • You can also use OkHttp:

    1. Introducing dependencies:
      	<dependency>
      		<groupId>io.github.openfeign</groupId>
      		<artifactId>feign-okhttp</artifactId>
      		<version>10.1. 0</verrsion>
      	</dependency>
      Copy the code
    2. Add configuration to application.yml:
  • Another optimization is to lower the log level. The lower the log level, the less logs are printed and the higher the performance

7.14 Summary of Common Problems

  • Address: www.imooc.com/article/289…

Fault tolerance of services

8.1 Avalanche Effect

  • In our system, when a service goes down, when other services need to access the service, they will not get the result and will wait for the service to return the result until the call times out. Each an access request is a thread resources, when the service call number is overmuch, can cause a lot of resources is not released, could lead to consumer service also goes down, so on will cause an avalanche effect, was caused by a service outage other service system resources are occupied by the continuous consumption is not release, causing a series of cascading failure.

8.2 Common fault tolerance schemes

  1. Setting timeout
  2. Set the current limit
  3. Warehouse wall mode:

    In this boat, for example, each cabin is independent. When one cabin floods, it does not cause all the cabins to flood and sink the ship. Each Controller acts as a “cabin”

  4. The circuit breaker
    1. Refer to our daily switch, when the power consumption exceeds the threshold, it will trip;
    2. Three state conversion of short-circuit device:

8.3 Fault tolerance using Sentinel

  • What is Sentinel?
    • It is a lightweight fault-tolerant library
  • Introduction:
    1. Introducing dependencies:

      <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>  </dependency>Copy the code
    2. The introduction of physical

      	<dependency>
      		<groupId>org.springframework.boot</groupId>
      		<artifactId>spring-boot-starter-actuator</artifactId>
      	</dependency>
      Copy the code
    3. Application. Yml adds configuration to expose endpoints:

    4. Access localhost: service port number/skeletonoid /sentinel, and the following screen appears. The configuration is complete:

8.4 Sentinel Console

  • Console setup:
    • (address) [github.com/alibaba/Sen…].
    • Version selection: depending on our dependency version or using the latest version is ok, if in production environment, preferably the dependency is the same as the console version;
    • Usage:
      1. download

      2. Pass it to the server and run the following command to start:

      3. To access the web page: IP /8080/#/login, enter the account password: sentinel

      4. Add configuration:

        Spring: cloud: sentinel: transport: #8080
        Copy the code

Sentinel is lazy loading

8.5 Flow control Rules

  • QPS and the number of threads are the filter criteria, which way to filter. Flow control is carried out when the single-machine threshold reaches more or less;

  • There are three flow control modes: direct, associated and link. Direct is the most common mode. When limiting traffic, it applies directly to the interface. And flow control effect is effective in three forms; Fast failure is also the most common type, where the direct interface returns failure when the threshold is reached. The flow control mode – association means that when the single-machine threshold of the path accessing the entry resource is triggered, the selected flow control effect will be triggered by this interface. The link indicates that only the data from the interface triggers the traffic limiting rule. Warm up is the hot wait, which will complete the triggering effect after a specified time; Queuing is not to return failure, but to queue, one finished, to process another.

  • Warm Up

    • It allows traffic to increase slowly.
  • Wait in line:

8.6 Detailed description of downgrade Rules

  • RT degradation rule illustration:

    • Graph one:

    • Figure 2:

    RT the default maximum 4900 ms, through – Dcsp. Sentinel. Statistic. Max. RT = XXX to modify

  • Downgrade-abnormal ratio:

  • Demotion-outliers:

    Note: The time window < 60 seconds may cause problems. For example, we set the time window to 10 seconds. If the number of outliers still triggers the downgrade within the trigger downgrade, it may cause another downgrade

  • Source:

    • com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule#passCheck
  • Official explanation:

  • Note: Sentinel does not have half-open status at present.

8.7 Hotspot Rule Details

  • Hotspot rules limit traffic on the specified interface. You can limit the current in unit time of a certain parameter, a certain type, and a certain value of this parameter of the interface; It can protect some hotspot interfaces, so it is called hotspot rule.
  • Define a hotspot rule:
    1. Define the interface:
    2. Configuring hotspot Rules
  • Applicable scenarios:
    1. QPS very high interface or parameter
    2. The parameter must be a basic type or String
  • Source code address:
    • com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowChecker#passCheck

8.8 System Rules

  • Here is:

  • System – Load:

  • System-rt, thread count, entry QPS:

  • Source code address:

    • com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowChecker#passCheck

8.9 Description of Authorization Rules

  • Summary:
    • Authorization rules can authorize service consumers, restrict access, and so on
  • Here is:

8.10 Code Configuration Details

  • Note for configuration method: Note for configuration method
  • It makes sense to extend Sentinel and learn its architecture, or to configure it directly from this interface.

8.11 Analysis of communication principle between Sentinel and console

  • Question:
    1. How does the console get monitoring information about microservices?
      • Timing push to console
    2. When you configure rules with the console, how does the console send the rules to individual microservices?
  • Related source code:

8.12 Console Configuration Items

  • Here is:
  • Action: To start the Sentinel JAR, pass in the parameters as shown in the following figure:

8.13 Sentinel API details

  • Here is:

    This will count the flow control and execute the code in the CATCH if the limit threshold is exceeded;

  • Monitor other anomalies:

  • Source:

    • Here is:

      The end needs to close the stream

    • Separate traffic limiting rules can be applied to services from this source:

  • The main API:

    1. SphU: Defines resources so that they can be monitored and protected
    2. Tracer: Do statistics for any other exceptions we want
    3. ContextUtil: Targeting the source

We can do this later in simpler ways, but based on the code shown above;

8.14 SentinelResource Notes

  • Use this annotation to complete the function of 8.13, Handwritten address: handwritten address

  • Code illustration:

    These blocks can handle limiting or degrading traffic. Degradation can be handled using the fallback keyword alone, and then writing a method similar to block. The upgrade to Sentinel 1.6 can handle Throwable

  • Related source code:

    • com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect
    • com.alibaba.csp.sentinel.annotation.aspectj.AbstractSentinelAspectSupport

8.15 RestTemplate Integrates Sentinel

  • Just use the @SentinelRestTemplate annotation
    • Here is:

      The switch is configured in application.yml

  • The code looks like this:
    1. Annotate the RestTemplate:

    2. Use the RestTemplate in the code, which will get the monitoring information in Sentinel. If you change the switch to false, it will not get the information.

8.16 Feign integrated Sentinel

  • Use Fallback:
    1. Add configuration:

    2. Point to a class in Feign:

    3. Complete this class:

  • Using FallbackFactory, it is more powerful and can get exceptions:
    1. Define the class:
    2. Feign references this FallbackFactory:
  • Source:
    • org.springframework.cloud.alibaba.sentinel.feign.Sentinel

8.17 Summary of posture used in Sentinel

8.18 Rule Persistence 01 Pull Mode

  • Note address: Note address

If you are configured to refresh, there may be no data display. You can access the interface first and then come back to refresh, because it is lazy loading mode.

  • Advantages and disadvantages of pull mode:

8.19 Rule Persistence 02- Push mode

  • Note address: Note address

8.20 Sentinel is used in the production Environment

8.21 Cluster Traffic Control

  • Cluster flow control official document: hppts://github.com/alibaba/Sentinel/wiki/ cluster flow control

Gateway Gateway provides the same effect as cluster flow control with simpler performance.

8.22 Extended Sentinel01 — Error page optimization

  • Using UrlBlockHandler can optimize error messages so that we can tell whether the interface is due to limiting or degrading traffic or an exception;
  • Code operation:
    1. Inheritance interface:

    2. Write code:

    3. Returns the result

8.23 Extended Sentinel02 — To enable source differentiation

  • Source:

  • Specify the source configuration rule:

8.24 Extended sentinel03-restful URL

  • Use the following code to make all paths with the same resource name use the same traffic limiting rule:

  • Configure resources as shown in the following figure:

8.25 Extended Sentinel04 — Looking At the Essence through the Appearance

  • To sum up:

8.26 Configuration Items Summary

  • Configuration item Summary notes: Configuration item summary notes

8.27 Conclusion of this chapter: Talk about common fault tolerance schemes again

  • Common fault tolerance schemes:
    • timeout
    • Current limiting
    • Warehouse wall mode (not implemented) : Sentinel does not use the warehouse wall mode, but it specifies which threads are used where, thus achieving a similar effect to the warehouse wall mode
    • The circuit breaker