SpringCloudAlibaba Microservice [Practical] | Nacos Registration Center

Table of contents

1: Nacos Registration Center

1. Understand and install Nacos

2. Quick Start with Nacos

3. Nacos service hierarchical storage model

①Nacos service hierarchical storage model

②NacosRule load balancing 

③Load balancing based on weight

4. Nacos environment isolation

2: Comparison between Nacos and Eureka


tips: A few days ago, I suddenly discovered a giant artificial intelligence learning website. It is easy to understand and humorous. I can’t help but share it with everyone. Interested students can StudyArtificial Intelligence Learning Website

1: Nacos Registration Center

We have already explained the Eureka registration center, now let’s learn about the Nacos registration center! In fact, Nacos can also be used as a configuration center, which will be described in detail later!

Dubbo

SpringCloud

SpringCloudAlibaba

Registration center

zookeeper、Redis

Eureka、Consul

Nacos、Eureka

Service remote call

Dubbo protocol

Feign (http protocol)

Dubbo、Feign

Configuration center

none

SpringCloudConfig

SpringCloudConfig、Nacos

service gateway

none

SpringCloudGateway、Zuul

SpringCloudGateway、Zuul

Service monitoring and protection

dubbo-admin, weak function

Hystix

Sentine

1. Understand and install Nacos

Nacos Alibaba’s product (needs to download, install, start), now available inSpringCloud a component of. Compared with Eureka (Spring has been integrated), it has richer functions and is more popular in China! Nacos is a dynamic service discovery, configuration management and service management platform that makes it easier to build cloud native applications. In SpringCloud Alibaba, we use nacos for service registration discovery and service configuration management.

Step 1: Download the installation package

On the GitHub page of Nacos, a download link is provided to download the compiled Nacos server or source code:

GitHub main page: https://github.com/alibaba/nacos

GitHub’s Release download page:https://github.com/alibaba/nacos/releases

Step 2: Unzip and configure

This time, version 1.4.1 of Nacos is used. The unzipped directory is as follows:

The default port of Nacos is 8848. If other processes on your computer occupy port 8848, please try to close the process first. Of course, you can also modify the default port of Nacos in application.properties in the conf directory

Step 3: Start

The startup of Nacos is very simple, enter the bin directory, the structure is as follows

Open cmd and execute the following command to start

startup.cmd -m standalone # 单机启动

Step 4: Visit and log in

Enter the address in the browser:http://127.0.0.1:8848/nacosAnd then:

The account and password are both nacos: the page after login

2. Quick Start with Nacos

The steps for using Nacos are basically the same as those for Eureka. Just configure the original Eureka with Nacos!

Step one:Add in the cloud-demo parent projectspring-cloud-alilbaba-dependicesManagement dependencies

Review:Eureka created a sub-project eureka-server under the cloud-demo parent project: introduce the eureka-server dependency, add the @EnableEurekaServer annotation to the startup class, Configure the port number, server name, and server address in application.yaml!

Background: We know that SpringCloud is a one-stop solution for microservices and a collection of many components, and becausealmost all components in SpringCloudWe use Netflixproducts, most of which have entered the stage of stopping updating or maintenance. We need some other components to replace them. Based on this, SpringCloud Alibaba was born, of which Nacos is one of them, so we need to introduce the SpringCloudAlibaba dependency first.

<!--引入SpringCloudAlibaba依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-dependencies</artifactId>
    <version>2.2.6.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

Second step: Comment out the original order-service and user-service dependencies on eureka, and add nacosy dependencies

Note:The dependencies introduced by service providers and service consumers are allnacos-discovery dependencies

<!--nacos客户端依赖 -->
<dependency>
     <groupId>com.alibaba.cloud</groupId>
     <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

Step 3:Modify the application.yml files in user-service and order-service, comment out the eureka address, and add the nacos address (the server name still uses the original one)

# nacos服务端地址
spring:
  cloud: 
    nacos:
      server-addr: localhost:8848

Step 4:Start and test

3. Nacos service hierarchical storage model

①Nacos service hierarchical storage model

Scenario:Assume that a certain function user-service now has multiple instances. Previously, it was a two-tier concept: oneservice a>There can be multipleinstances! However, it is not safe to deploy all instances in one computer room, so multiple instances are deployed in multiple computer rooms. The Nacos service hierarchical storage model introduces this concept, turning instances in the same computer room into a cluster; so for the Nacos model:The first level is the service, the lower level is the cluster, and finally the Example.

Service cross-cluster calling problem

Note: When calling services, choose the services of the local cluster as much as possible. The delay of cross-cluster calls is high; when the local cluster is inaccessible, visit other clusters!

Service cluster properties

Go back to the Nacos console to view the cluster properties at this time: default (meaning none)

How to set the properties of a service cluster? Add the discovery attribute to the original configuration of user-service

spring:
  cloud: 
    nacos:
      server-addr: localhost:8848 # nacos服务端地址
      discovery: 
        cluster-name: HZ # 配置集群名称,也就是机房位置,例如:HZ,杭州

At this time uservice-service prepares 3 real columns: UserApplication---8081, UserApplication1---8082, UserApplication2---8083; first start UserApplication---8081 and UserApplication1---8082 according to the above configuration; then add the above After changing the cluster name to SH, start UserApplication2---8083

Add cluster attributes to order-service

spring:
  cloud: 
    nacos:
      server-addr: localhost:8848 # nacos服务端地址
      discovery: 
        cluster-name: HZ # 配置集群名称

②NacosRule load balancing 

We have already analyzed that we should use local clusters as much as possible and avoid cross-domain access; so at this time, we will test whether three consecutive visits will all access the HZ cluster and not the SH cluster?

Run result: It is still a round-robin access, and there is no priority to access the local one; it needs to be modified at this time Load balancing (originally the default is round-robin scheduling )!

In order-serviceSet the load balancing IRule to NacosRule, this rule will first look for services in the same cluster as itself:

user-service:
  ribbon:
    NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # 负载均衡规则 

At this time, visit three times in a row again:

Prioritize access to the local cluster, and load balance in a [random] manner based on the local cluster!

What if the local service HZ is stopped at this time?

The local service cannot be found. It will be accessed across clusters and can be accessed successfully, but you will receive a warning!

Summarize

① Prioritize the list of service instances in the same cluster;

② If the local cluster cannot find the provider, it will look for it in other clusters and a warning will be reported;

③After determining the list of available instances, use random load balancing to select instances;

③Load balancing based on weight

In actual deployment, the following scenario will occur:

The performance of server equipment is different. Some instances are located on machines with better performance, while others are worse. We hope that machines with good performance will bear more user requests;Nacos provides weights Configure to control the access frequency. The weight value is generally between 0-1. The greater the weight, the higher the access frequency!

Step 1: You can set the weight value of the instance in the Nacos console. First, select the edit button behind the instance.

Step 2: Set the weight to 0.1. The test can find that the frequency of 8081 being accessed is greatly reduced.

Thinking: What is the use when the weight is 0?

In fact, when the weight is 0, the server will not be accessed at all; when we upgrade the version, we can first set the weight to 0 to access other servers. After the version upgrade is completed, set the weight to a very small value and put it in the extreme Tested with a small number of customers; the test is no problem and extensive upgrade services are being carried out!

Summarize

①The Nacos console can set the weight value of the instance, between 0 and 1;

② For multiple instances in the same cluster, the higher the weight, the higher the frequency of access;

③If the weight is set to 0, it will not be accessed at all;

4. Nacos environment isolation

Nacos is first of all a registration center and a data center; so when Nacos manages data and services, it has the concept of environmental isolation.

Environment isolation-namespace

①The outermost layer of service storage and data storage in Nacos is a thing called namespace, which is used for outermost isolation;

② There will be a group attribute (group) inside the namespace, and multiple instances of the same namespace can be grouped; those with high business relevance can be placed in the same group;

Group contains specific services, services Below is the cluster, and below the cluster is the instance;

In fact, there is a default namespace public on the Nacos console, and all our original instances are placed in this group.

 Requirement: Put order-service into a new namespace

Step 1: Create a namespace on the Nacos console to isolate different environments

Step 2: Fill in a new namespace information

Step 3: After saving, you will see the id of this namespace in the console.

Note: The id does not need to be filled in, it can be automatically generated based on the UUID.

Step 4: Modify the application.yml file and add the namesapce namespace

spring:
  cloud: 
    nacos:
      server-addr: localhost:8848 # nacos服务端地址
      discovery:
        cluster-name: SH # 集群
        namespace: e70e8b60-ea7e-40e0-a995-0b714190f7bd # 填写ID ,命名空间

Step 5: After restarting order-service, check the console again

public namespace:

dev namespace:

Step 6: Access order-service at this time. Because the namespace is different, user-service will not be found.

The browser cannot find the service:

Note: There are actually three services user-service in public, but order-service in dev, different namespaces cannot be accessed (We learned earlier that different clusters can be accessed, but a warning will be reported )!

The console will report an error:

Summarize:

①Each namespace namespace has a unique id;

②When setting the namespace of the service, write the id instead of the name;

③ Services under different namespaces are invisible to each other;

2: Comparison between Nacos and Eureka

So far we have studied two registration centers: Eureka and Nacos. Let’s compare and study them!

Details:The classes we created earlier are temporary instances by default

Analyze the similarities and differences between Eureka and Nacos from the execution process

same

① When the service provider starts, whether it is Eureka or Nacos, it will submit information to the registration center, and the registration center will save this information Come down;

②When consumers need it, they will go to the registration center to pull it regularly; in fact, this The pulling action does not need to be done every time. The service consumer will cache the pulled information into a list(Repulse every 30 seconds);

③After the consumer gets the service list, the load balancer selects a remote call provider;

different

The first difference: health monitoring of service providers, Nacos will Divided into: Temporary instances and Non-temporary instances. For temporary instances, heartbeat detection is used (this is consistent with Eureka, but the frequency is different, nacos will be slower), If found, it will be eliminated; for non-temporary instances, Nacos will not require a heartbeat, and Nacos will actively inquire , found that will be marked as unhealthy, waiting for recovery, and will not be eliminated.

The second difference: consumer pull service, Eureka uses scheduled pull (every 30 seconds) , cannot be updated in time; Nacos will actively push change messages, ; if Nacos finds that a service is down, it will be pushed immediately Push to consumers and update in time. Eureka uses pull, while Nacos is a combination of pull+push

When a service is registered to Nacos, you can choose to register it as a temporary or non-temporary instance, which is set through the following configuration:

spring:
  cloud: 
    nacos:
      server-addr: localhost:8848 # nacos服务端地址
      discovery:
        cluster-name: SH # 集群
        namespace: e70e8b60-ea7e-40e0-a995-0b714190f7bd #填写ID,指定命名空间
        ephemeral: false #设置为非临时实例

①The default is a temporary real column. If order-service is closed at this time, this service will be killed.

② Modify epemeral to false, change it to non-instance, and close the service at this time

Will not be removed, waiting for recovery!

Summarize

1. What Nacos and eureka have in common

① Both support service registration and service pulling;

② All support service providers’ heartbeat method for health testing;

2. The difference between Nacos and Eureka

①Nacos supports the server to actively detect the provider status: temporary instances adopt heartbeat mode, and non-temporary instances adopt active detection mode; temporary instances with abnormal heartbeats will be removed, while non-temporary instances will not be removed. Eureka uses heartbeat detection, and abnormalities are directly eliminated.

②Nacos supports message push mode for service list changes. The service list is updated more timely. It is a combination of pull and push. Eureka only pulls data and cannot update it in time.

③The Nacos cluster uses AP mode by default. When there are non-temporary instances in the cluster, CP mode is used; Eureka uses AP mode.

Note:AP/CP mode means that in a distributed system, data availability and consistency cannot be achieved at the same time a>. P (Partition tolerance) partition fault tolerance , C (Consistency) consistency, A (Availability) availability, so there is a trade-off between availability and consistency. Among them

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/133205225