当前位置:网站首页>Nacos detailed explanation, something

Nacos detailed explanation, something

2022-04-23 16:21:00 Herdsman farmer

Enjoy it , Develop habits , WeChat search 【 Small farmers 】 Follow me for more information , In the wind and rain , The farmer is waiting for you , I'm glad to be your friend .
Project source address : The official account replied nacos, You can get the source code for free

What is microservice

In understanding Nacos Before , So let's see , What is microservice ? stay 2014 In the year , One is called Martin Fowler( Martin · Fowler ) My God , The concept of micro service is proposed , Definition : Microservices are small services made up of a single application , Independent process and lightweight processing , Services are designed according to business functions , Deploy in a fully automated manner , Can be used with other services HTTP API communicate , At the same time, the service will be centrally managed with the smallest scale , Services can be implemented in different programming languages, databases and other components .

The evolution of Architecture

I remember when small farmers first worked , At that time, services were mostly single applications , Maybe a little better , The cluster will be deployed , Is to deploy multiple machines in a complete project , Well, with the development of the Internet , The carrying capacity and scale of website applications are also expanding , As a result, our system architecture is constantly changing , From the early days of the Internet to today , The system architecture has generally experienced ( Monomers ——> vertical ——> Distributed ——>SOA——> Microservices ), As shown in the figure below :
 Insert picture description here

1、 Monomer architecture

In the beginning , Most services are in a single architecture , It is to concentrate all function points on one project ( application ) Inside , Unified development and deployment , This kind of development 、 Deployment and maintenance costs are relatively low .

  • The benefits of this , The project structure is simple , The easier , Suitable for projects with a small number of users , The development cost is relatively low , Because they are deployed on one node , Maintenance is also convenient
  • Weakness is , All functions are concentrated in one project , As the business grows , There will be more and more code and functions , It is difficult to support a large project for development and maintenance , High module coupling between projects , Low fault tolerance , For different functional modules, the optimization and scalability are low .

2、 Vertical application architecture

The so-called vertical application architecture , Is to change from a single application to multiple applications , To improve efficiency , For example, the supply chain system can be divided into : Commodity system 、 Order system 、 Performance system 、 Portal system 、 Procurement system, etc .

  • The advantage is that , After the project is split, the flow sharing is realized , Solve the concurrency problem to some extent , Different business modules can be optimized and expanded , At the same time, different systems will not affect each other , Improve fault tolerance .
  • shortcoming : Systems exist with each other , Cannot call each other , Systems are independent of each other , It will cause redundancy of some functions .

3、 Distributed systems

With the increase of business , In the vertical application architecture, there are more and more redundant codes , You need to pull out redundant code , Make it into a separate business layer for processing , Become a separate service , The control layer calls unused business layer services to complete different business functions .
It can be understood that a project is divided into two parts: presentation layer and service layer , The service layer implements business logic , The presentation layer handles page interaction .

  • advantage : Extract common functions as service layers , It can improve the reuse rate of code
  • shortcoming : The coupling between systems is high , The call relationship is complex

4、SOA framework

The disadvantage of distributed system is that its call is complex , When we have more and more services or when a service is under too much pressure, we need to expand the level and load balance , For resource scheduling and management, you need to use SOA(Service Oriented Architecture) As the core , The governance center can also help us solve the problem of different agreements between services .

  • advantage : Use the Governance Center (ESB\dubbo) It can solve the automatic call of call management between services
  • shortcoming : There will be certain dependencies between services , If there is an error in a certain link, it will have a great impact , The service relationship is complex , Operation and maintenance deployment is difficult

5、 Microservice architecture

Microservice architecture is... In some programs SOA The next step in the development of Architecture , It strengthens the service “ A complete split ”, The purpose is to improve efficiency , In microservice Architecture , The deployment of each service must not affect each other at the same time , Microservice architecture is more lightweight 、 Lightweight .

Microservice architecture and SOA Differences in Architecture

  1. Microservice architecture processing is more sophisticated , A module only processes the corresponding functions , Let professional people do professional things
  2. Each service is deployed independently , Services do not affect each other
  3. stay SOA Database storage sharing may occur in the schema , Microservices emphasize that each service is an independent database , Ensure that the connections between each service do not affect each other
  4. Microservice project architecture is better than SOA The architecture is more suitable for Internet companies ( Fast development 、 More efficient version iteration 、 More finely )

The experience of micro services in life

It is said that art comes from life , Then technology also comes from life ! Please give an example of
for example :
When we went to roll the string , Usually only one or two people , Centralized cashier 、 entertain 、 Cook in one , And when we go to the hotel , There will be a special reception attendant 、 cashier 、 The cook 、 Dishwasher, etc , Let professional people do professional things !

 Insert picture description here
The benefits of microservices are , Be able to atomize and split Services , Package independently 、 Deployment and upgrade , It can ensure clear task division between microservices , It's good for expansion , However, the technical cost of microservice distributed system development is relatively high , For example, consider fault tolerance 、 Distributed lock 、 Distributed transactions and so on , More complex .

Nacos brief introduction

Nacos (Naming Configuration Service) Belong to Spring Cloud Alibaba Under the technology stack , Set dynamic service discovery 、 Configuration and service management platform , Used to build meta native applications . among Service discovery is one of the most critical components in microservice architecture ,Nacos Provides a set of easy-to-use features , It can help us realize dynamic service discovery more quickly 、 To configure 、 Metadata and traffic management .

What is? Nacos

Registry Center + Configuration center = Nacos

Why use Nacos?

Registration center comparison

 Insert picture description here

CAP Model

Here we have to mention a very important theory , Namely CAP Model , These are also the three core elements considered in distributed system design :

  • Uniformity (Consistency): The instance of the same request at the same time returns the same result , All data should be consistent
  • Usability (Availability): The read and write requests of all instances can get correct responses within a certain period of time
  • Partition tolerance (Partition tolerance): In the network exception ( The cable is broken 、 Equipment failure 、 Downtime ) Under the circumstances , The system can still provide normal service

That's all CAP principle ( also called CAP Theorem ), But the above three situations cannot be satisfied at the same time , Distributed system design is considering to meet P( Partition tolerance ) On the premise of C( Uniformity ) still A( Usability ), That is what we are familiar with AP and CP

CP principle ( Partition tolerance + Uniformity )

CP The principle belongs to the principle of strong consistency , The data that can be queried by all nodes should be consistent at any time , Several nodes form a logical shared area , The updated data of a node will be synchronized to other data nodes immediately , Successful results can only be returned after data synchronization is completed , However, in the actual operation process, network failure is inevitable , If there is no communication between several service nodes at this time, an error will occur , Sacrifice the principle of availability (A)

AP principle ( Partition tolerance + Usability )

AP The principle belongs to the principle of weak consistency , As long as there are surviving nodes in the cluster , Then all requests sent can get the correct details , In the data synchronization operation, even if some nodes do not successfully realize data synchronization, they will return success , This sacrifices the principle of consistency (C), It can be applied to scenes where the network environment is not very good .

about Nacos for , Support CP and AP Dynamic switching between two modes , The default is AP

Switch command :curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP'

Nacos Similar to the front desk of our hotel , First of all, after the rooms in the hotel are cleaned and qualified, they will register at the service desk , So when a guest comes to the hotel , Just go through the front desk to find the room you can enter , There is no need to wait , You can check into the hotel quickly

【 room ——> service 】
【 Reception ——> Nacos】
【 guest ——> user 】

The registration and discovery mechanism provided by the server can help guests find a suitable room more quickly .
If there is no hotel without a front desk , When guests enter, they need to find a suitable room by themselves , Because the guest doesn't know the situation of each room , It is not possible to determine which room is a room with service conditions , Guests can only find one by one , laborious , At the same time, this is unreasonable

 Insert picture description here
In microservices , Software services are independent , But ultimately serve the customer as a whole , Software also needs to communicate with each other and call methods , The party that initiates the communication call method within the microservice architecture , We call it “ Serving consumers ”, The server that provides remote methods is called “ Service providers ”, Often in order to improve system performance , Multiple servers will be provided as Service providers , At this time, the process of service consumers looking for service providers , It's similar to the process of users looking for rooms , To help Serving consumers Fast discovery Service providers , In the microservice framework, we will introduce Registry Center , Registry Center It's similar to the front desk of a hotel , Provide registration and discovery functions in software services , Service providers Will register in the registration center first , Declare that you can provide external services , and Serving consumers Just find the services you can use through the registry , You can use the service quickly , The registration center realizes the function of rapid cooperation between service provision and service consumption .

Nacos build

Official website address :https://nacos.io/zh-cn/index.html
Document address :https://nacos.io/zh-cn/docs/quick-start.html
Download address :https://github.com/alibaba/nacos/releases
 Insert picture description here

It is generally recommended that we use the stable version , The official will also state in the document
 Insert picture description here
After downloading, unzip and use
 Insert picture description here
Carry out orders :
linux/Mac:

sh startup.sh -m standalone

Windows:

startup.cmd -m standalone

PS: Be careful nacos The file path must be in English , Otherwise start will report an error

nacos The default database is embedded cmdb, We can also create a local database and modify the configuration file to point to the local database ( recommend ).

After the startup is successful , We visit :http://localhost:8848/nacos
The default username and password is :nacos/nacos
As shown in the figure below, it indicates that we started successfully !
 Insert picture description here

Nacos Building the server

Nacos Registry Center

Service discovery is one of the key components in microservice architecture . In such an architecture , Manually configuring the list of services for each client can be a daunting task , And makes dynamic expansion extremely difficult .Nacos Discovery Help you automatically register your service with Nacos The server ,Nacos The server will track the service and dynamically refresh the service list . Besides ,Nacos Discovery Some metadata of the service instance , Such as mainframe 、 port 、 health examination URL、 Home page, etc. register to Nacos

official API file :https://spring.io/projects/spring-cloud-alibaba#learn

Some students will say , Small farmers, i english Not so good , Don't worry , Isn't there a translation on the browser now , Translate directly !!!
 Insert picture description here

Create project

We need to create an aggregation project , So if you need to add a new Nacos service , Add sub modules directly
Create a new parent project :spring-cloud-alibaba
Create a new subclass project :cloud-alibaba-nacos-9001

POM

Parent item

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2021.0.1.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

In the subitem , introduce Nacos Discovery Register for services / Find out

<dependency>
   <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

YML

server:
  port: 9001
spring:
  application:
    name: nacos-provider
  cloud:
    discovery:
      server-addr: localhost:8848

management:
  endpoint:
    web:
      exposure:
        include: '*'

Start class :

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

@SpringBootApplication
@EnableDiscoveryClient // Need to add this annotation 
public class CloudAlibabaNacos9001Application {

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

Test class :

/**
 * @program: spring-cloud-alibaba
 * @ClassName DemoController
 * @description:
 * @author:  Small farmers 
 * @create: 2022-03-27 17:08
 * @Version 1.0
 **/
@RestController
public class DemoController {
    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/muxiaonong")
    public String getServerPort(){
            return "hello Nacos Discovery"+serverPort;
    }
}

When we start the service , You can see in the service list , See us start the service

 Insert picture description here
Reference resources cloud-alibaba-nacos-9001 Create a new service cloud-alibaba-nacos-9002

Nacos Consumer load balancing

Create a new subclass project :cloud-alibab-consumer-8083
Pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.muxiaonong</groupId>
        <artifactId>spring-cloud-alibaba</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.muxiaonong</groupId>
    <artifactId>cloud-alibab-consumer-8083</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cloud-alibab-consumer-8083</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
            <version>3.1.0</version>
        </dependency>

    </dependencies>

</project>

At the same time, we also need to add subclass descriptions in the parent project

<modules>
    <module>cloudalibaba-nacos-9001</module>
    <module>cloudalibaba-nacos-9002</module>
    <module>cloudalibab-consumer-nacos-8083</module>
</modules>

yml

server:
  port: 8083
spring:
  application:
    name: nacos-consumer
  cloud:
    discovery:
      server-addr: localhost:8848

Start class

@SpringBootApplication
@EnableDiscoveryClient
public class CloudAlibabConsumer8083Application {

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

nacos-provider: Service registrant
nacos-consumer: Serving consumers
 Insert picture description here

Calls between services

If we want the consumer of our service to call the service provider , It needs to pass Ribbon To call .

What is? Ribbon

Spring Cloud Ribbon It's based on HTTP and TCP Client load balancer , be based on Netflix Ribbon Realization , adopt Spring Cloud Encapsulation , It allows us to easily integrate service-oriented Rest Template requests are automatically converted into client load balancing service calls , Although it is a tool class library , No independent deployment is required , It exists in almost every Spring Cloud Built into the microservices and infrastructure , For calls between services ,AP The request forwarding of the gateway needs to go through Ribbon Load balancing to achieve , and Ribbon The main function of : Get the corresponding service list from the registration server and access the corresponding service in the way of load balancing

because Nacos It's integrated Ribbon, So if we want to use , Just import Spring Cloud Alibaba Nacos The dependency can be used directly .

This needs to be noted that nacos since 2020 What will not be integrated after the version is Netflix, There is no ribbon 了 , If an error is reported that the service cannot be found because , You used a load balancing algorithm , But no ribbon 了 , It doesn't know which service to use .
So here we just need to import spring-cloud-starter-loadbalancer Rely on it

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

 Insert picture description here

Ribbon The basic use of

about Ribbon Make a remote call , We usually use RestTemplate, among getForObject It's the most common method , We just need to add... To the startup class RestTemplate It can be used normally

 	@Bean
    @LoadBalanced //nacos Integrated ribbon
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

When body When is an object , This can be done directly :
User result = restTemplate.getForObject(uri, User.class);

There is no need to pay attention to the request response body Other than , This function is very easy to use , Can be one less from Response In order to get body Steps for . Three different overloaded implementations are provided

url: Represents the called target Rest Interface location , Multiple service providers register the same name ,Ribbon Will automatically find one of the service providers , And call the interface method . This is the load balancing function
responseType: return type ,JavaBean Type or JavaBean An array type
urlVariables: Pass to url Dynamic parameters of , When using parameters, you need to be in url You need to use {1}、{2}、{3} Carry out parameter occupancy , In this way, the passed parameters will automatically replace the placeholder

getForObject(String url, Class responseType, Object ... urlVariables)
getForObject(String url, Class responseType, Map urlVariables)
getForObject(URI url, Class responseType)

Nacos Load balancing

If you want our consumers consuomer Call the service provider 9001 and 9002, Load balancing is what we need .
yml

server:
  port: 8083
spring:
  application:
    name: nacos-consumer
  cloud:
    discovery:
      server-addr: localhost:8848

#  The name of the service provider 
service-url:
  nacos-user-service: http://nacos-provider

Configure... On the startup class restTemplate

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

Test class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
 * @program: spring-cloud-alibaba
 * @ClassName DemoController
 * @description:
 * @author:  Small farmers 
 * @create: 2022-04-04 16:11
 * @Version 1.0
 **/
@RestController
public class DemoController {

    @Autowired
    private RestTemplate restTemplate;

	// Access service name 
    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @GetMapping(value = "/consumer/nacos")
    public String getDiscovery(){
        System.out.println(serverURL);
        return restTemplate.getForObject(serverURL+"/muxiaonong",String.class);
    }

When we type in :http://localhost:8083/consumer/nacos,
You can see that 9001 and 9002 The corresponding switch shows
 Insert picture description here

Nacos Configuration center

We're talking about Registry Center + Configuration center = Nacos , In front of us, we will the Registration Center , Now let's talk about how to use Nacos As his configuration center

Why use Nacos Configuration center

1、 Configure the dynamic refresh of properties
2、 Centralized management of configuration files

Let's create a new sub item :cloud-alibaba-config-3377

pom file :

 <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

YML To configure :
Here we need to configure two , One is to register the current project with Nacos in , The other is to Nacos Read the configuration file with the specified suffix in
bootstrap.yml

# nacos To configure 
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos Address of service registration center 
      config:
        server-addr: localhost:8848 #Nacos As the configuration center address 
        file-extension: yaml # Appoint yaml Format configuration 

application.yml

spring:
  profiles:
     active: dev

The startup class is also added @EnableDiscoveryClient annotation

Test class :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: spring-cloud-alibaba
 * @ClassName DemoController
 * @description:
 * @author:  Small farmers 
 * @create: 2022-04-10 16:02
 * @Version 1.0
 **/
@RestController
@RefreshScope // Support Nacos Dynamic refresh of 
public class DemoController {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/config/info")
    public String getConfigInfo(){
        return configInfo;
    }
}

Nacos Configuration rules of

Official website :https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html

stay Nacos Spring Cloud in ,dataId The complete format is as follows

${prefix}-${spring.profiles.active}.${file-extension}
  • prefix The default is spring.application.name Value , You can also configure items through spring.cloud.nacos.config.prefix To configure the .
  • spring.profiles.active That is, the current environment corresponds to profile, For details, please refer to Spring Boot file . Be careful : When spring.profiles.active It's empty time , Corresponding connector - There will be no ,dataId The splicing format of becomes ${prefix}.${file-extension}
  • file-exetension To configure the data format of the content , You can use the configuration item spring.cloud.nacos.config.file-extension To configure the . Currently only supported properties and yaml type .
 ${spring.application.name}-${spring.profiles.active}.${file-extension}
 nacos-config-client-dev.yaml
  Microservice name - The current environment - File format 

And then we just need to Nacos You can create configuration items on the platform
 Insert picture description here
 Insert picture description here
 Insert picture description here
modify Nacos To configure , Automatically refresh without restarting the project

You can access it through a link
 Insert picture description here

Summary

It's not easy to create , Your one button three connection is my biggest motivation !!!

If you have questions or don't understand , Welcome to leave a message below , The small farmer saw , I will reply to you as soon as possible .

Fear of the infinite truth , further There is further joy , You come on ~

版权声明
本文为[Herdsman farmer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231612092957.html