Microservice architecture | 2.2 unified configuration management of Alibaba Nacos

preface

reference material:
<Spring Microservices in Action>
Principle and practice of Spring Cloud Alibaba microservice
"Spring cloud framework development tutorial in Silicon Valley of station B" Zhou Yang
Nacos official website

Nacos is committed to solving the problems of unified configuration, service registration and discovery in microservices. It provides a set of easy-to-use feature sets to help developers quickly realize dynamic service discovery, service configuration, service metadata and traffic management;

1. Basic knowledge of Nacos configuration center

1.1 functions of Nacos in configuration center

  • CRUD, version management, gray management, monitoring management, push track, aggregate data and other functions;

1.2 composition of Nacos configuration management Data ID

  • ${prefix}-${spring.profiles.active}.${file-extension};
  • The default is ${spring. Application. Name} - ${spring. Profiles. Active}$ {spring.cloud.nacos.config.file-extension};
    • prefix: the default is spring application. The value of name can also be set through the configuration item spring cloud. nacos. config. prefix to configure;
    • spring.profiles.active: the profile corresponding to the current environment. When spring profiles. When active is empty, the corresponding connector - will not exist, and the splicing format of dataId will become ${prefix}$ {file-extension};
    • File exception: configure the data format of the content through the configuration item spring cloud. nacos. config. File extension. Currently, only properties and yaml types are supported;

1.3 rollback mechanism configured by Nacos

  • Nacos will record the historical version of the configuration file, which is retained for 30 days by default. In addition, there is a one click rollback function, and the rollback operation will trigger the configuration update;

1.4 graphical management interface of Nacos configuration

  • Configuration management;

  • Namespace;

1.5 relationship among namespace, Group and Data ID

  • Similar to the package name and class name in Java, the outermost Namespace can be used to distinguish the deployment environment. Group and Data ID logically distinguish two target objects;

  • By default, Namespace=public, Group=DEFAULT_GROUP,Cluster=DEFAULT;

    • Namespace: it is mainly used to realize isolation and solve the isolation problem of multi environment and multi tenant data. For example, there are three environments: development, testing and production. Three namespaces can be created, and different namespaces are isolated;
    • Group grouping: different microservices can be divided into the same group to realize the mechanism of Data ID grouping management;
    • Data ID: usually used to organize and divide the configuration set of the system;
    • Cluster: a virtual partition of a specified microservice;
    • Instance: instance of micro service;
  • The official suggestion is to distinguish different environments through namespaces, while the Group can focus on data grouping at the business level;

1.6 CRUD configured by Nacos

  • It is mainly realized by providing Open API interface or SDK;

Action on configurationSDKOpen APIexplain
Publish configurationpublic boolean publishConfig(String dataId, String group, String content) throws NacosExceptionPOST: /nacos/v1/cs/configsSave the configuration to the Nacos Config Server
Delete configurationpublic boolean removeConfig(String dataId, String group)throws NacosExceptionDELETE: /nacos/v1/cs/configsDeletes the specified configuration from the configuration center
Get configurationpublic string getConfig(String dataId, String group, long timeoutMs) throws NacosExceptionGET: /nacos/v1/cs/configsRead configuration from Nacos Config Server
Listening configurationpublic void addListener(String dataId, String group, Listener listener)POST: /nacos/v1/cs/configs/listenerSubscribe to the configuration of interest and receive an event when the configuration changes

1.7 long polling mechanism of Nacos dynamic monitoring

  • Generally speaking, there are two mechanisms for dynamic listening:
Comparison itemPull mechanismPush mechanism
explainThe client actively pulls data from the serverThe server actively pushes the data to the client
shortcomingReal time data cannot be guaranteed; When the server configuration is not updated for a long time, the scheduled task of the client will make some invalid PullIf the number of clients is large, the server needs to consume a lot of memory resources to save each connection; A heartbeat mechanism is required to maintain each connection state
  • Nacos's solution: long polling mechanism:

  • If the client initiates a Pull request, the server checks whether the configuration has changed after receiving the request:
    • Change: return to change configuration;
    • No change: set a scheduled task, delay the execution for 29.5s, and add the current client long polling connection to the allSubs queue;
  • Configuration changes within 29.5s:
    • No change in configuration: wait 29.5s and trigger the automatic inspection mechanism to return to the configuration;
    • Configuration change: at any time within 29.5s, a configuration change will trigger an event mechanism. The task listening to the event will traverse the allSubs queue, find the ClientLongPolling task corresponding to the changed configuration item, and return the changed data through the connection in the task. It is equivalent to completing a PUSH operation;
  • Long polling mechanism combines the advantages of Pull mechanism and Push mechanism;

1.8 source code analysis of Nacos configuration center

2. Basic configuration of Nacos

Take the Data ID scheme as an example. For more details, please refer to point 3 3. Three schemes of Nacos loading configuration in this chapter;

2.1 download Nacos server

2.2 introduction of POM XML dependency file

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

2.3 modifying yml configuration files

  • bootstrap.yml:
# nacos configuration
server:
  port: 18082

spring:
  application:
    name: nacos-config-client     #Must be part of the Nacos configuration management Data ID field
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848     #Nacos service registry address
      config:
        server-addr: localhost:8848     #Nacos as configuration center address
        file-extension: yaml     #Specifies the configuration of yaml format
        
        # prefix: hhh     #The prefix of the Data ID, if not specified, is nacos-config-client-dev.yaml. When specified, it is hhh-dev.yaml
        # refresh: true      #Whether to refresh dynamically
        
        # group: DEFAULT_GROUP     #Specify group
        # namespace: PUBLIC     #Specify namespace ID
  • application.yml:
spring:
  profiles:
    active: dev # Represents the development environment

2.4 add comments on the main program class

  • @EnableDiscoveryClient: use other components (Nacos, zookeeper, Consul) as the registry;

2.5 write business class

  • Only one controller is written here as an example:
@RestController
@RefreshScope //Make the configuration under the current class support the dynamic refresh function of Nacos
public class ConfigClientController{
    @Value("${config.info}")
    private String configInfo;

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

2.6 adding configuration information to Nacos server

  • Create and add configuration in Nacos server:



  • Start the service and call the interface: http://localhost:18082/config/info Obtain configuration information;

2.7 error report and unable to assemble bean

  • Note: if If the data IDS configured by yml and Nacos server do not match, the ${config.info} in the ConfigClientController class will not be found, and finally the error that ConfigClientController cannot be assembled will be reported, as follows:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.configClientController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'config.info' in value "${config.info}"
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:380) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:356) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:389) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:186) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	at org.springframework.cloud.context.scope.refresh.RefreshScope.eagerlyInitialize(RefreshScope.java:134) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.cloud.context.scope.refresh.RefreshScope.start(RefreshScope.java:125) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:119) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:73) ~[spring-cloud-context-2.1.2.RELEASE.jar:2.1.2.RELEASE]
	at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
	......

3. Three schemes of Nacos loading configuration

  • The following is a description of bootstrap The modification of YML can be replaced by configuring the JVM environment at startup. Use the following command:
  • -Dspring.profiles.active=${profile}

3.1 Data ID scheme

  • Create a new environment with three data IDS:

  • Specify spring profile. After restarting the service, you can see that the configuration has been switched to another environment:
spring:
  profiles:
    active: prod

3.2 Group scheme

  • Create an environment for three groups:

  • Specify spring profile. Active and spring cloud. nacos. config. Group, restart the service, and you can see that the configuration has been switched to another environment:
  • application.yml:
spring:
  profiles:
    active: info #modify
  • bootstrap.yml:
server:
  port: 18082
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 
      config:
        server-addr: localhost:8848
        file-extension: yaml
        group: PROD_GROUP #newly added

3.3 Namespace scheme

  • Create an environment with two namespaces:


  • Clone / create several configuration files to the new namespace;

  • Specify spring profile. Active and spring cloud. nacos. config. Group, restart the service, and you can see that the configuration has been switched to another environment:
  • application.yml:
spring:
  profiles:
    active: dev #modify
  • bootstrap.yml:
server:
  port: 18082
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 
      config:
        server-addr: localhost:8848
        file-extension: yaml
        group: DEFAULT_GROUP #newly added
        namespace: 48b2da7d-0b26-4c15-907b-9a379db8f7de #The ID of the new namespace will be given when creating a new namespace


last

Newcomer production, if there are mistakes, welcome to point out, thank you very much! Welcome to the official account and share some more everyday things. If you need to reprint, please mark the source!

Keywords: Distribution Spring Cloud Microservices

Added by scottbarry on Fri, 21 Jan 2022 12:16:14 +0200