Learn to use Nacos

1Nacos as a service registry

1.1 Service providers based on Nacos

Module—>cloudalibaba-provider-payment9001
POM.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud1000</artifactId>
        <groupId>com.zs.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-provider-payment9001</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

YML.xml

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

Main startup class, add annotations @EnableDiscoveryClient

package com.zs.cloudalibabaproviderpayment9001;

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

@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaProviderPayment9001Application {

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

Business class

package com.zs.cloudalibabaproviderpayment9001.controller;

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;

/**
 * @author zhaoshuai06 <[email protected]>
 * Created on 2021-06-07
 */
@RestController
public class PaymentController {
    @Value("${server.port}")
    private String serverPort;

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

Test
Access the service interface http://localhost:9001/payment/nacos/1 to
view the Nacos console, the list of services

Insert picture description here


To demonstrate load balancing, create a new cloudalibaba-provider-payment9002

1.2 Service consumers based on Nacos

Module—>cloudalibaba-provider-payment9001
POM.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud1000</artifactId>
        <groupId>com.zs.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-consumer-nacos-order83</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

YML

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

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

Main startup class, add annotation @EnableDiscoveryClient

package com.zs.cloudalibabaconsumernacosorder83;

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

@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaConsumerNacosOrder83Application {

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

Business class

package com.zs.cloudalibabaconsumernacosorder83.controller;

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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhaoshuai06 <[email protected]>
 * Created on 2021-06-08
 */
@RestController
public class OrdeNacosController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${server-url.nacos-user-service}")
    private String serverURL;

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

Configuration class

package com.zs.cloudalibabaconsumernacosorder83.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;

/**
 * @author zhaoshuai06 <[email protected]>
 * Created on 2021-06-08
 */
@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

test

View Nacos console, service list,

Insert picture description here


access service interface http://localhost:83/consumer/payment/nacos/13
83, access 9001/9002, polling load OK

Insert picture description here

2Nacos as a service configuration center

2.1Nacos as the configuration center-basic configuration

Module—>cloudalibaba-config-nacos-client3377
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud1000</artifactId>
        <groupId>com.zs.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-config-nacos-client3377</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--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>
    </dependencies>
</project>

YML

Insert picture description here


bootstrap.yaml

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

application.yaml

spring:
  profiles:
    active: dev # 表示开发环境

Main startup class, add annotation @EnableDiscoveryClient

package com.zs.cloudalibabaconfignacosclient3377;

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

@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaConfigNacosClient3377Application {

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

Business class, add annotation @RefreshScope, support automatic refresh

package com.zs.cloudalibabaconfignacosclient3377.controller;

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;

/**
 * @author zhaoshuai06 <[email protected]>
 * Created on 2021-06-08
 */
@RestController
@RefreshScope //支持Nacos的动态刷新功能。
public class ConfigClientController {
    @Value("${config.info}")
    private String configInfo;

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

Add configuration in Nacos, nacos-config-client-dev.yaml, the content is

config:
    info: nacos config center,version = 2 from nacos config center, nacos-config-client-dev.yaml, version=3
Insert picture description here


Pay attention to the editing test of Data Id:

Insert picture description here


Insert picture description here


Insert picture description here


Test
Visit http://localhost:3377/config/info to
modify the configuration, call again, and the test will be refreshed automatically

Insert picture description here

2.2 Nacos as the configuration center-classification configuration

Insert picture description here


Insert picture description here


Insert picture description here



DataID scheme Specify spring.profile.active and the DataID of the configuration file to read different configurations in different environments.
Nacos configuration file name rules

${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
Insert picture description here


Insert picture description here
Insert picture description here


Insert picture description here


The group solution
bootstrap.yaml specifies spring.cloud.nacos.config.group, which corresponds to the Group in Nacos.

Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here


Namespace solution
bootstrap.yml specifies spring.cloud.nacos.config.namespace, which corresponds to the ID of the Namespace in Nacos.

Insert picture description here


Insert picture description here
Insert picture description here


Insert picture description here


Insert picture description here


Insert picture description here

3Nacos cluster and persistent configuration (important)

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

Insert picture description here

3.1 Configure mysql database

The stand-alone mode supports MySQL
before version 0.7. When in stand-alone mode, nacos uses an embedded database to store data, which is not convenient for observing the basic situation of data storage. The 0.7 version adds the ability to support mysql data source, the specific operation steps:
1. Install the database, version requirements: 5.6.5+
2. Initialize the mysql database, the database initialization file: nacos-mysql.sql

/Users/zhaoshuai/softeware/nacos/conf/nacos-mysql.sql

3. Modify the conf/application.properties file, add support for mysql data source configuration (currently only supports mysql), and add the url, user name and password of the mysql data source.

spring.datasource.platform=mysql

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

Then start nacos in stand-alone mode, all the data written to the embedded database in nacos is written to mysql

sh startup.sh -m standalone
Insert picture description here


Insert picture description here