Introduction to Nacos Configuration Center, Introduction to Remote Configuration and Dynamic Refresh Configuration Function

Introduction

Nacos has the functions of registration center and configuration center. First, we will introduce the configuration center separately.

Nacos provided for storing configuration and which his metadata key / value store , the server and the client provides support for the external configuration of the distributed system. Using Spring Cloud Alibaba Nacos Config, you can centrally manage the external property configuration of your Spring Cloud application in Nacos Server .

​ Spring Cloud Alibaba Nacos Config is an alternative to Spring Cloud Config Server and Client . The concepts on the client and the server have the same abstraction as Spring Environment and PropertySource. In the special bootstrap stage, the configuration is loaded into the Spring environment. As the application goes from development to testing to production through the deployment pipeline, you can manage the configuration between these environments and ensure that the application has everything that it needs to run during migration. Please refer to the official website of Nacos for how to obtain and start Nacos .

Question :

Project integration

There are also two ways to introduce Nacos Config, namely Aliyun Java Initializr introduction and Maven pom.xml dependency. It is officially recommended to use Aliyun Java Initializr to introduce Nacos Config to simplify the dependencies between components.

Pom.xml example

<?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>
    <groupId>com.laker</groupId>
    <artifactId>config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>config</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <spring-cloud-alibaba.version>2.2.2.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <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-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.laker.config.ConfigApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Start Nacos Server

Refer to Solve the problem of slow domestic download speed of Nacos Server Download start

The default username and password are: nacos

Nacos Server add configuration

  • Nacos Server configuration
  • bootstrap.yml 配置
  • Code configuration

The overall picture is as follows:

Insert picture description here

Introduction of common functions

It only describes how to use it, and the principle refers to the following article.

Use Nacos Config as Spring Cloud distributed configuration

Start class

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

Configuration class

@RestController
@RequestMapping("/config")
public class ConfigController {
    
    

    @Value("${laker.name}")
    private String lakerName;

    @RequestMapping("/get")
    public String get() {
    
    
        return lakerName;
    }
}

verification

Browser access: http://ip:port/config/get.

Use Nacos Config to achieve Bean dynamic refresh

​ Nacos Confg supports the standard Spring Cloud @ RefreshScopefeature, that is, after the application subscribes to a Nacos configuration, when the configuration content changes, the properties of the binding configuration in the Refresh Scope Beans will be conditionally updated. The so-called condition means that the Bean must:

  • Required condition : the declared class of Bean must be marked with @RefreshScope
  • Choose one condition :
    • Properties (non-static fields) are marked @Value
    • @ConfigurationProperties Bean

​ In addition, Nacos Confg also introduced Nacos Client's underlying data change monitoring interface,
namely com.alibaba.nacos.api.config.listener.Listener. The following content will discuss these three different
usage scenarios.

Nacos Client: Nacos client API, which is also the underlying dependency of Nacos Config

Bean @Value property dynamic refresh

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
    
    

    @Value("${laker.name}")
    private String lakerName;

    @RequestMapping("/get")
    public String get() {
    
    
        return lakerName;
    }

    @PostConstruct
    public void init() {
    
    
        System.out.printf("---[init]--- laker name : %s ", lakerName);
    }
}

@ConfigurationProperties Bean property dynamic refresh

  • 激活 @ConfigurationProperties Bean @EnableConfigurationProperties(
    User.class)。
  • Dependency injection of User Bean through @Autowired.
@RefreshScope
@ConfigurationProperties(prefix = "laker")
public class User {
    
    
    private String name;
    private int age;
}

Start class

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

Use Nacos g Config to monitor the dynamic refresh of Bean properties

​ As mentioned earlier, com.alibaba.nacos.api.config.listener.Listener is the Nacos ClientAPI standard configuration listener interface. Since it only listens to the configuration content and cannot directly communicate with the Spring system, it needs the help of Spring Cloud Alibaba Nacos Config API NacosConfigManager

@SpringBootApplication
public class NacosConfigSampleApplication {
    
    
    @Autowired
    private NacosConfigManager nacosConfigManager;

    public static void main(String[] args) {
    
    
        SpringApplication.run(NacosConfigSampleApplication.class, args
        );
    }
    @Bean
    public ApplicationRunner runner() {
    
    
        return args -> {
    
    
            String dataId = "laker-dev.yaml";
            String group = "DEFAULT_GROUP";
            nacosConfigManager.getConfigService().addListener(dataId, group, new
                    AbstractListener() {
    
    
                        @Override
                        public void receiveConfigInfo(String configInfo) {
    
    
                            System.out.println("[Listener] " + configInfo);
                        }
                    });
        };
    }
}

[Listener] laker:
  name: laker1222222

reference:

  • Spring Cloud Alibaba from entry to actual combat.pdf
Reach out for party benefits: Spring Cloud Alibaba from entry to actual combat.pdf Download

Pay attention to my public account [ Java Interviewer ], reply: 100 can be downloaded

Catalog of this series

Guess you like

Origin blog.csdn.net/abu935009066/article/details/112667479