The address of the project: https://github.com/coderTomato/mscloud_H

1. Nacos profile

1.1 Why Nacos?

The first four letters are Naming and Configuration respectively, and the last s is Service

1.2 what is

Nacos, a dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud native applications, is a combination of registry and configuration center

1.3 can do

Replace Eureka as service registry replace Config as service configuration center

1.4 go down

https://github.com/alibaba/Nacos

1.5 Comparison among registries

2. Install and run Nacos

Maven Maven Maven Maven Maven Maven Maven Maven Maven Maven Run directly under the bin directory of startup. CMD MAC perform sh startup. Sh -m standalone command to run after a successful direct access to the http://localhost:8848/nacos user name password is nacos

3. Nacos is demonstrated as a service registry

3.1 Official documents https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html

3.2 NacOS-based service providers

Create a new module cloudBaba-provider-Payment9001 POM file

<dependencies>

    <! -- nacos-discovery-->

    <dependency>

        <groupId>com.alibaba.cloud</groupId>

        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

    </dependency>

    <! -- introduce your own API generic package -->

    <dependency>

        <groupId>com.jd.springcloud</groupId>

        <artifactId>cloud-api-commons</artifactId>

        <version>${project.version}</version>

    </dependency>

    <! -- boot 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>

    <! -- devtools-->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <scope>runtime</scope>

        <optional>true</optional>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies>

Copy the code

Yml file

server:

  port: 9001



spring:

  application:

    name: nacos-payment-provider

  cloud:

    nacos:

      discovery:

        server-addr: localhost:8848



management:

  endpoints:

    web:

      exposure:

        include: '*'

Copy the code

The main start class

@EnableDiscoveryClient

@SpringBootApplication

public class PaymentMain9001 {

    public static void main(String[] args) {

        SpringApplication.run(PaymentMain9001.class, args);

    }

}

Copy the code

Business class

@RestController

public class PaymentController {



    @Value("${server.port}")

    private String serverPort;



    @GetMapping("/payment/nacos/{id}")

    public String getPayment(@PathVariable("id") Integer id){

        return "nacos registry, serverPort:"+serverPort+"\t id"+id;

    }

}

Copy the code

3.3 test

  • Start the NACOS registry
  • Then start the project CloudAlibaba-provider-Payment9001
  • Go to http://localhost:9001/payment/nacos/1
  • Check it out at the NACOS registry



    Nacos service registry + service provider 9001 are OK

3.4 Creating a 9002 based on the 9001 to demonstrate nacOS load balancing

3.5 NacOS-based service consumers

Create a new module cloudBaba-consumer-nacos-Order83

Pom file

<dependencies>

    <! -- nacos-discovery-->

    <dependency>

        <groupId>com.alibaba.cloud</groupId>

        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

    </dependency>

    <! -- introduce your own API generic package -->

    <dependency>

        <groupId>com.jd.springcloud</groupId>

        <artifactId>cloud-api-commons</artifactId>

        <version>${project.version}</version>

    </dependency>

    <! -- boot 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>

    <! -- devtools-->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <scope>runtime</scope>

        <optional>true</optional>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies>

Copy the code

Yml file

server:

  port: 83





spring:

  application:

    name: nacos-order-consumer

  cloud:

    nacos:

      discovery:

        server-addr: localhost:8848



# Name of microservice the consumer will access (microservice provider registered with NACOS)

service-url:

  nacos-user-service: http://nacos-payment-provider

Copy the code

The main start class

@EnableDiscoveryClient

@SpringBootApplication

public class OrderNacosMain83 {



    public static void main(String[] args) {

        SpringApplication.run(OrderNacosMain83.class, args);

    }

}

Copy the code

Business class

package com.jd.springcloud.alibaba.config;



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(a);

    }

}

Copy the code

controller

@RestController

public class OrderNacosController {



    @Value("${service-url.nacos-user-service}")

    private String serverURL;



    @Resource

    private RestTemplate restTemplate;



    @GetMapping("/consumer/payment/nacos/{id}")

    public String paymentInfo(@PathVariable("id") Long id){

        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);

    }

}

Copy the code

The test starts the NACOS console, then the 9001/9002 and finally the Consumer83

The server consumers are registered with NACOS

Go to http://localhost:83/consumer/payment/nacos/13

3.6 Service registry comparison

Nacos supports switching between Ap and CP modes

C means that all nodes see the same data at the same time, while A means that all requests receive responses

When to choose which mode to use?

Generally speaking, the AP mode can be selected if the service instance does not need to store service level information and is registered with NACOS-Client and can keep heartbeat reporting. Current mainstream services, such as Spring Cloud and Dubbo services, are applicable to AP mode. AP mode reduces consistency for service availability, so only temporary instances can be registered in AP mode

If want to edit or store configuration information in the service level, the CP is a must, K8S and DNS service is applicable to the CP mode, the CP mode for register persistent instance, at this time in Raft agreement for cluster operation mode, the mode register before the instance must first registration service, if the service does not exist, will return an error.

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

Copy the code

4. Demonstration of Nacos as service configuration center

4.1 Nacos as the Configuration Center – Basic Configuration

4.1.1 Create a new module cloudbaba-config-nacos-client3377

Pom file

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

    <! -- introduce your own API generic package -->

    <dependency>

        <groupId>com.jd.springcloud</groupId>

        <artifactId>cloud-api-commons</artifactId>

        <version>${project.version}</version>

    </dependency>

    <! -- boot 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>

    <! -- devtools-->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <scope>runtime</scope>

        <optional>true</optional>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies>

Copy the code

Yml file

bootstrap.yml

server:

  port: 3377



spring:

  application:

    name: nacos-config-client



  cloud:

    nacos:

      discovery:

        server-addr: localhost:8848 #Nacos service registry address

      config:

        server-addr: localhost:8848 #Nacos as the configuration center address

        file-extension: yaml # specify yamL configuration

Copy the code

application.yml

spring:

  profiles:

    active: dev # indicates the development environment

Copy the code

The main start class

@SpringBootApplication

@EnableDiscoveryClient

public class NacosConfigClientMain3377 {



    public static void main(String[] args) {

        SpringApplication.run(NacosConfigClientMain3377.class, args);

    }

}

Copy the code

Business class ConfigClientController

@RestController

@RefreshScope // Dynamic refresh of Nacos is supported

public class ConfigClientController {



    @Value("${config.info}")

    private String configInfo;



    @GetMapping("/config/info")

    public String getConfigInfo(){

        return configInfo;

    }

}

Copy the code

Add configuration information in Nacos

(1) The theory of matching rules in Nacos the composition format of datAID in Nacos and the matching rules in SpringBoot configuration files

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


(2) Practical operation of matching rules in Nacos

(2.1) Configuration added


(2.2) Corresponding configuration on the Nacos interface


Setting DataId summary:

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

Prefix defaults to the value of spring.application.name

Spring.profile. active indicates the profile corresponding to the current environment. You can configure this parameter using the spring.profile.active configuration item.

File - exetension as the configuration of content data format, through the spring configuration items. Cloud. Nacos. Config. The file - the extension to the configuration

Copy the code

Summary:


(2.3) Historical configuration

Nacos keeps historical versions of configuration files for 30 days by default and has a one-click rollback feature

4.1.2 test

Before starting, you need to have the corresponding YAML configuration file under the nacOS Client – Configuration Management – Configuration Management column


Run the main boot class of Cloud-config-nacos-Client3377

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

4.1.3 Built-in Dynamic Refresh

Modify the YAML configuration file in Nacos and call the interface to view the configuration again to find that the configuration has been refreshed

4.2 Nacos as the configuration center – Classification configuration

4.2.1 Multi-environment and Multi-project management

Question 1: In actual development, a system usually prepares the dev development environment, test test environment, and 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 is started?

Q.2 A large distributed microservice system will have many microservice sub-projects, and each microservice project will have corresponding development environment, test environment, pre-release environment, formal environment… So how do you manage these microservice configurations

4.2.2 Graphical management interface of Nacos
4.2.3 Relationship among Namespace+Group+DataID? Why is it designed this way?

What is the

The outermost namespace of the package name and class name in Java is used to distinguish the deployment environment, and the Group and DataID logically distinguish the two target objects

DEFAULT Namespace=public, Group=DEFAULT_GROUP, Cluster =DEFAULT Nacos the DEFAULT Namespace is public, Namespace is used to implement isolation. In development, test, and production environments, we can create three namespaces that are isolated from each other

Group is DEFAULT_GROUP by default. Group can Group different microservices into the same Group. A Service can contain multiple clusters. The DEFAULT Cluster of Nacos is DEFAULT. A Cluster is a virtual partition of a specific microservice. For example, for disaster recovery, the Service microservice is deployed in the Hangzhou machine room and the Guangzhou machine room respectively. In this case, the Service microservice in the Hangzhou machine room can be named as a cluster name HZ, and the Service microservice in the Guangzhou machine room can be named as a cluster name (GZ), and the microservices in the same machine room can be invoked with each other as far as possible. To improve performance and finally instance, which is an instance of a microservice

4.2.4 Loading configuration in three schemes
4.2.4.1 DataID scheme

Specify spring.profile.active and DataID for configuration files to read different configuration in different environments default space + default grouping + new dev and test DataID


The spring.profile.active property enables configuration files to be read in multiple environments

test

Go to http://localhost:3377/config/info

4.2.4.2 Group plan

Achieve environment differentiation through Group -> Create Group


Create a new configuration file, DataID, on the NACOS GUI console


The bootstrap+application configuration is as follows


Add a group configuration under config. It can be DEV_GROUP or TEST_GROUP

4.2.4.3 Namespace solution

Create a Namespace for dev/test


Go back to Service Management – Service List view


Set this parameter based on the domain name configuration



YML file

bootstrap.yml

cloud:

  nacos:

    discovery:

      server-addr: localhost:8848 #Nacos service registry address

    config:

      server-addr: localhost:8848 #Nacos as the configuration center address

      file-extension: yaml # specify yamL configuration

      group: DEV_GROUP

      namespace: ff0dcf7d- 06d4- 47cd-a1eb0feb8a396cec

Copy the code

application.yml

spring:

  profiles:

    #active: info

    active: dev # indicates the development environment

Copy the code

5. Nacos cluster and persistence configuration

5.1 Official Website

https://nacos.io/zh-cn/docs/cluster-mode-quick-start.html The default Nacos uses an embedded database for data storage. So if you start multiple Nacos nodes in the default configuration, the data store is inconsistent. To address this issue, Nacos has adopted a centralized storage approach to support clustered deployment, currently only supporting MySQL storage.

Nacos supports three deployment modes

  • Single-machine mode – Used for testing and single-machine trial
  • Cluster mode – Used in production environments to ensure high availability
  • Multi-cluster mode – Used in multi-DATA center scenarios

https://nacos.io/zh-cn/docs/deployment.html

5.2 Nacos Persistent Configuration Description

5.2.1 Nacos ships with the embedded database Derby by default

https://github.com/alibaba/nacos/blob/develop/config/pom.xml

5.2.2 Switch configuration steps between Derby and mysql
  • Nacos-server-1.1.4 /nacos/conf Find the nacos-mysql. SQL script and run it
  • Properties file in nacos-server-1.1.4/nacos/conf, add support for mysql data source configuration (currently only mysql), add mysql data source URL, user name, and password.
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

db.user=root

db.password=root

Copy the code
5.2.3 Starting Nacos, you can see the new empty record interface, which used to record Derby

5.3 Linux Production Environment Configuration of Nacos+MySQL

It is expected that 1 Nginx+3 NACOS registries +1 mysql will be required

5.3.1 Nacos Download Linux version

The website https://nacos.io/zh-cn/docs/cluster-mode-quick-start.html


Download address: https://github.com/alibaba/nacos/releases/download/1.1.4/nacos-server-1.1.4.tar.gz

5.3.2 Cluster Configuration Procedure

1. Configure the mysql database on the Linux server. Go to the nacos decompression directory, copy the nacos-mysql. SQL script content in the nacos/conf directory, and paste it to the mysql database on your Linux server

2. Application. The properties configuration

Make a backup copy

[robin@node02 conf]

[robin@node02 module] vi nacos/conf/application.properties


3. Configure cluster.conf for the NACOS cluster on the Linux server

Back it up

[robin@node02 conf]

[robin@node02 conf] vim cluster.conf

#it is ip

192168.. 56103.: 3333

192168.. 56103.: 4444

192168.. 56103.: 5555

thisIPCan't write 127. 0. 01.That must beLinuxThe commandhostname -irecognisableIP

Copy the code


4. Edit the startup script startup.sh of Nacos to accept different startup ports

Implement way


5. Configuration of Nginx as a load balancer

Modify the nginx configuration file nginx.conf

[root@node02 conf]# vi /usr/local/nginx/conf/nginx.conf


Start the nginx

[root@node02 sbin]# ./nginx -c /usr/local/nginx/conf/nginx.conf

6. As of this point, 1 Nginx+3 NACOS registries +1 mysql

Start the NACOS cluster


Check whether the startup is successful



Create a new configuration test



Mysql on Linux server inserts a record


The test accessed NacOS through nginx

http://192.168.56.103:1111/nacos/#/login

5.3.3 test

The microservice CloudBaba-provider-Payment9002 starts registering in the NACOS cluster

Yml file

spring:

  application:

    namenacos-payment-provider

  cloud:

    nacos:

      discovery:

        server-addr: 192168.. 56103.: 1111# fornginxPort 1111 of the cluster

Copy the code

Results The NACOS cluster was successfully registered