SpringCloud-Alibaba Nacos

Nacos

Introduction

Why is it called Nacos?

  • The first four letters are the first two letters of Naming and Configuration, and the last s is Service.

what is

  • A dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications.

  • Nacos: Dynamic Naming and Configuration Service

  • Nacos is the combination of registration center + configuration center -> Nacos = Eureka+Config+Bus

what can you do

  • Replace Eureka as a service registry

  • Replace Config as a service configuration center

where to go

  • https://github.com/alibaba/nacos/releases
  • https://nacos.io
  • [Official website document](https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring cloud alibaba nacos_discovery)

various registries

Service Registration and Discovery Framework CAP model console management Community activity
Eureka AP support Low (2.x version closed source)
Zookeeper CP not support middle
consul CP support high
Nacos AP support high

Install Nacos

  • The local Java8+Maven environment is OK first
  • Download Nacos from the official website
  • Unzip the installation package and directly run startup.cmd in the bin directory
  • Use sublime Text to change the cluster startup to a stand-alone startup and change set MODE="cluster" to set MODE="standalone"

insert image description here

  • After the command runs successfully, visit http://localhost:8848/nacos directly, and the default account password is nacos
  • results page
    insert image description here

use nacos

Service Provider Registration

official document

New Module

名字: cloud-alibaba-provider-payment9001

Parent POM
<dependencyManagement>
    <dependencies>
        <!--spring cloud alibaba 2.1.0.RELEASE-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.1.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
This module POM
 <dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
YML
server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'
main boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class PaymentMain9001 {
    
    
    public static void main(String[] args) {
    
    
            SpringApplication.run(PaymentMain9001.class, args);
    }
}
business class
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/payment")
public class PaymentController {
    
    
    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id) {
    
    
        return "nacos registry, serverPort: "+ serverPort+"\t id"+id;
    }
}

test

  • http://localhost:9001/payment/nacos/1
  • nacos console
  • nacos service registration center + service provider 9001 are OK

insert image description here

In order to demonstrate the load balancing of nacos in the next chapter, refer to 9001 to create a new 9002

  • New cloud-alibaba-provider-payment9002
  • 9002 Other steps you understand
  • Or by chance, if you don’t want to create a new repetitive manual labor, you can use the IDEA function to directly copy the virtual port mapping
    insert image description here

start 9002
insert image description here

Service consumer registration and load

New Module

Home: cloud-alibaba-consumer-nacos-order83

POM
 <dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Why does nacos support load balancing? Because spring-cloud-starter-alibaba-nacos-discovery contains netflix-ribbon package.

YML
server:
  port: 83

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

#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider
main boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

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

ApplicationContextConfig

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

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

OrderNacosController

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/consumer")
public class OrderNacosController {
    
    
    
    @Resource
    private RestTemplate restTemplate;

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

    @GetMapping(value = "/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id){
    
    
        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);
    }
}

test

  • Start the nacos console
    insert image description here

  • http://localhost:83/Eonsumer/payment/nacos/13

    • 83 access 9001/9002, polling load OK

Nacos service registration center comparison improvement

Panorama of Nacos
insert image description here

Nacos and CAP

Comparison of Nacos and other registry features
insert image description here

Nacos service discovery instance model
insert image description here

Nacos supports switching between AP and CP modes

C is that the data seen by all nodes at the same time is consistent; and the definition of A is that all requests will receive responses.

When to choose which mode to use?

Generally speaking, if you do not need to store service level information and the service instance is registered through nacos-client and can keep heartbeat reporting, then you can choose the AP mode. The current mainstream services such as Spring cloud and Dubbo services are all applicable to the AP mode. The AP mode weakens the consistency for the possibility of service. Therefore, only temporary instances are supported in the AP mode.

If you need to edit or store configuration information at the service level, then CP is a must, and K8S service and DNS service are suitable for CP mode. In CP mode, registration of persistent instances is supported. At this time, the Raft protocol is used as the cluster operation mode. In this mode, the service must be registered before registering the instance. If the service does not exist, an error will be returned.

Toggle command:

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

Service Configuration Center

basic configuration

new module

名字:cloud-alibaba-config-nacos-client3377

POM

 <dependencies>
        <!--nacos-config-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!--nacos-discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--web + actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

YML

Nacos is the same as springcloud-config. When the project is initialized, the configuration must be pulled from the configuration center first. After the configuration is pulled, the normal start of the project can be guaranteed.

The loading of configuration files in springboot has a priority order, and bootstrap has a higher priority than application

bootstrap
# nacos配置
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置


# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml

# nacos-config-client-test.yaml   ----> config.info
application
spring:
  profiles:
    active: dev # 表示开发环境
    #active: test # 表示测试环境
    #active: info

main boot

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

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

business 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;

@RestController
@RefreshScope //支持Nacos的动态刷新功能。
public class ConfigClientController{
    
    
    @Value("${config.info}")
    private String configInfo;

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

Add configuration information in Nacos

The composition format of dataid in Nacos and the matching rules with the SpringBoot configuration file

official document

Note: The reason why spring.application.name needs to be configured is because it is part of the dataId field of Nacos configuration management.

In Nacos Spring Cloud, the complete format of dataId is as follows:

${prefix}-${spring-profile.active}.${file-extension}
  • prefixThe default spring.application.namevalue is , and can also be configured through configuration items spring.cloud.nacos.config.prefix.
  • spring.profile.activeIt corresponds to the current environment profile. For details, please refer to the Spring Boot documentation. Note: When spring.profile.activeit is empty, the corresponding connector - will also not exist, and the splicing format of datald becomes${prefix}.${file-extension}
  • file-exetensionTo configure the data format of the content, it can be spring .cloud.nacos.config.file-extensionconfigured through configuration items. Currently only the propertiesand yamltypes are supported.
  • Realize automatic configuration update through Spring Cloud native annotation @RefreshScope

Final formula:

${spring.application.name)}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

New configuration
insert image description here

Nacos interface configuration correspondence - set DataId
insert image description here

Note: In nacos, it must be written as yaml. Consistent with the one in bootstrap.

Configuration summary

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-yyKdqBQD-1658544652233)(SpringCloud/image-20220720134616452.png)]

test

  • Before starting, you need to have a corresponding yaml configuration file under the nacos client-configuration management-configuration management column

  • Run the main startup class of cloud-config-nacos-client3377

  • Call interface to view configuration information - http://localhost:3377/config/info

Comes with dynamic refresh

Modify the yaml configuration file in Nacos, call the interface to view the configuration again, and you will find that the configuration has been refreshed.

The relationship between namespace, grouping and DataID

Problem - Multi-environment multi-project management

Question 1:

In actual development, usually a system will prepare

  • dev development environment

  • test test environment

  • prod production environment.

How to ensure that the service can correctly read the configuration file of the corresponding environment on Nacos when the specified environment starts?

Question 2:

A large-scale distributed micro-service system will have many micro-service sub-projects, and each micro-service project will have a corresponding development environment, test environment, pre-release environment, and formal environment... so how to manage these micro-service configurations?

Nacos graphical management interface
insert image description here
insert image description here

What is the relationship between Namespace+Group+Data ID? Why is it designed this way?

1. What is it?

Similar to the package name and class name in Java, the outermost namespace can be used to distinguish the deployment environment. Group and DataID logically distinguish two target objects.

2. The situation of the three
insert image description here

Default: Namespace=public, Group=DEFAULT_GROUP, default Cluster is DEFAULT

  • The default Namespace of Nacos is public, and Namespace is mainly used to achieve isolation.
    • For example, we now have three environments: development, testing, and production environments. We can create three Namespaces, and different Namespaces are isolated from each other.
  • Group defaults to DEFAULT_GROUP, and Group can divide different microservices into the same group
  • Service is a microservice: a Service can contain multiple Clusters (clusters), Nacos default Cluster is DEFAULT, and a Cluster is a virtual division of a specified microservice.
    • For example, for disaster recovery, the Service microservice is deployed in the Hangzhou computer room and the Guangzhou computer room respectively. At this time, a cluster name (HZ) can be given to the Service microservice in the Hangzhou computer room, and a cluster name (HZ) can be given to the Service microservice in the Guangzhou computer room. (GZ), you can also try to make the microservices in the same computer room call each other to improve performance.
  • The last is Instance, which is an instance of microservices.

DataID configuration

Specify spring.profile.active and the DatalD of the configuration file to read different configurations in different environments

Default space + default group + create two DatalDs of dev and test

  • New dev configuration DatalD
    insert image description here

  • New test configuration DataId
    insert image description here

Two configuration files under the same group
insert image description here

Group configuration

Realize environment differentiation through Group - create a new Group
insert image description here

Create a new configuration file DatalD on the nacos graphical interface console
insert image description here

bootstrap+application

Add a group configuration under config. Can be configured as DEV_GROUP or TEST GROUP
insert image description here

Namespace configuration

Create a new dev/test Namespace
insert image description here

Go back to service management-service list view
insert image description here

Fill in according to the domain name configuration
insert image description here

yml

# nacos配置
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置
        group: TEST_GROUP
        namespace: a5019df9-577b-4b87-a5a4-98158dc84405  #<------------指定namespace


# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml

# nacos-config-client-test.yaml   ----> config.info

Cluster Architecture and Persistence

official document

Official website structure diagram

Cluster deployment architecture diagram

Therefore, when open source, it is recommended that users put all service lists under a vip, and then hang them under a domain name

http://ip1:port/openAPI directly connects to the ip mode, and the machine needs to modify the ip before it can be used.

http://VIP:port/openAPI mounts the VIP mode, directly connects to the vip, and hangs the real ip of the server below, which is not readable.

http://nacos.com:port/openAPI domain name + VIP mode, good readability, and easy to change ip, recommended mode
insert image description here

The official website translation of the above picture, the real situation
insert image description here

According to the above, we need mysql database .

Official website description

By default, Nacos uses an embedded database to store data. Therefore, if you start multiple Nacos nodes under the default configuration, there will be consistency problems in data storage. In order to solve this problem, Nacos adopts a centralized storage method to support cluster deployment, and currently only supports MySQL storage.

Nacos supports three deployment modes

  • Standalone mode - for testing and single-player trials.

  • Cluster mode - used in production environments to ensure high availability.

  • Multi-cluster mode - for multi-data center scenarios.

stand-alone mode

Windows

cmd startup.cmd or double-click the startup.cmd file

Before version 0.7, nacos used an embedded database to store data in stand-alone mode, which made it inconvenient to observe the basic situation of data storage. The 0.7 version adds the ability to support mysql data source, the specific operation steps:

  • Install the database, version requirements: 5.6.5+
  • Initialize the mysq database, database initialization file: nacos-mysql.sql
  • Modify the conf/application.properties file, add support for mysql data source configuration (currently only supports mysql), add the url, user name and password of the mysql data source.
spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=UTC
db.user=nacos_devtest
db.password=youdontknow

Then start nacos in stand-alone mode, and all data written by nacos to the embedded database will be written to mysql.

cluster

Estimated need, 1 Nginx + 3 nacos registry + 1 mysql

official request

Please make sure it is installed in the environment using:

  1. 64 bit OS Linux/Unix/Mac, Linux system is recommended.
  2. 64 bit JDK 1.8+ ; Download.Configure .
  3. Maven 3.2.x + ; download.configure .
  4. 3 or more Nacos nodes can form a cluster.

link

Nacos Download for Linux

  • https://github.com/alibaba/nacos/releases/tag/2.0.3
  • nacos-server-2.0.3.tar.gz decompress and install

Cluster configuration steps (focus)

1. MySQL database configuration on Linux server

Where is the SQL script - directory nacos/conf/nacos-mysql.sql
insert image description here

Run on the Mysql database on your own Linux machine

2. application.properties configuration

Add the following content to set the data source

spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=UTC
db.user=root
db.password=1234

3. The cluster configuration cluster.conf of nacos on the Linux server

Sort out the different service port numbers of the 3 nacos concentrators, and set 3 ports:

  • 3333
  • 4444
  • 5555

You can make a copy of cluster.conf first. Misconfiguration on one side

cp cluster.conf.example cluster.conf

Modify cluster.conf

content

192.168.111.144:3333
192.168.111.144:4444
192.168.111.144:5555

Note that this IP cannot write 127.0.0.1, it must be hostname -ian IP that can be recognized by Linux commands
insert image description here

4. Edit the Nacos startup script startup.sh so that it can accept different startup ports

There is startup.sh in the /nacos/bin directory
insert image description here

Usually, the startup of the stand-alone version is ./startup.sh

However, when the cluster starts, we hope that we can pass different port numbers to start different nacos instances similar to shell commands of other software.
Command: ./startup.sh -p 3333 means to start the nacos server instance with port number 3333, which is consistent with the cluster.conf configuration in the previous step.

Modify content
insert image description here
insert image description here

Implementation modalities -startup.sh - p 端口号
insert image description here

Use the command to check whether the startup is successful:

ps -ef | grep nacos|grep -v grep|wc -l
insert image description here

Guess you like

Origin blog.csdn.net/m0_49683806/article/details/125944831