SpringCloudAlibaba configuration center: nacos-config

nacos-config configuration center

The code and notes of this project have been stored in the Gitee warehouse address: code, notes


Official documentation: https://github.com/alibaba/springcloudalibaba/wiki/Nacosconfig

Nacos provides a key/value store for storing configuration and other metadata, providing server-side and client-side support for externalized configuration in distributed systems. Using Spring Cloud Alibaba Nacos Config, you can centrally manage the external property configuration of your Spring Cloud application in Nacos Server.

1. Maintenance 2. Timeliness 3. Safety

springcloud config comparison

Three major advantages:

  • Springcloud config is used in conjunction with git in most scenarios. Dynamic changes also need to rely on the Spring Cloud Bus message bus to pass all client changes.
  • springcloud config does not provide a visual interface
  • nacos config uses long polling to update the configuration. Once the configuration changes, the process of notifying the provider is very fast, beating the original springcloud config in terms of speed.

1.1 Quick start

Click the plus sign to create a new configuration

Namespace: represents different environments , such as development, testing, and production environments.

Group: represents a certain project , such as XX medical project, XX e-commerce project

DataId: There are often several projects (microservices) under each project , and each configuration set (DataId) is the main configuration file of a project (microservice)

  • For example, create a new public order configuration, click Publish, and it will appear in the configuration list.

  • You can also directly check the configuration and click clone to other namespaces (environments)

Permission control

  • Start permissions: If you need to use permission configuration, modify application.properties to make it effective

1.2 Build nacos-config service

Implement dynamic changes in configuration through Nacos Server and spring-cloud-starter-alibaba-nacos-config

  • First create a new module

new->module->Next->Enter name->finish

  • Create a new startup class

    If namespace: public is specified, there will be a bug console that keeps printing ClientWorker

  • Create a new configuration class

  • Add dependencies
<!--NacosConfig依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
  • Get the configuration information in the startup class (you must add the bootstrap.properties configuration file to configure the Nacos Server address before using it)

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2023/03/19/16:36
 * @Description: 配置中心服务启动类
 */
@SpringBootApplication
public class ConfigApplication {
    
    
    public static void main(String[] args) {
    
    
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigApplication.class, args);
        String orderName = applicationContext.getEnvironment().getProperty("order.name");
        String num = applicationContext.getEnvironment().getProperty("order.num");
        System.out.println("order name :" + orderName + "; num: " + num);
    }
}
  • Add the bootstrap.yml configuration file to configure the Nacos Server address
spring:
  application:
    name: config-nacos
  cloud:
    nacos:
      server-addr: 192.168.13.1:8848
      username: nacos
      password: nacos
      config:
        namespace: public

Note that if you change the permissions to true in the configuration, you must configure the nacos username and password.

At this time, the configuration does not take effect and the console prints null.

2023-03-19 16:55:37.480  INFO 17536 --- [           main] c.a.nacos.client.config.impl.CacheData   : [fixed-192.168.13.1_8848-public] [add-listener] ok, tenant=public, dataId=config-nacos, group=DEFAULT_GROUP, cnt=1
order name :null; num: null

This is because the service name must be consistent with the dataId configured in nacos.

spring:
  application:
    name: com.zmz.order
  cloud:
    nacos:
      server-addr: 192.168.13.1:8848
      username: nacos
      password: nacos
      config:
        namespace: public

At this time, the configuration will take effect. Of course, if you want the service name to be inconsistent with the dataId, you must manually specify the dataId.

控制台:[add-listener] ok, tenant=public, dataId=com.zmz.order, group=DEFAULT_GROUP, cnt=1
order name : 蔡徐坤; num:  21

1.3 Config related configurations

The Nacos data model Key is uniquely determined by a triplet. Namespace defaults to an empty string, public namespace (public), and grouping defaults to

DEFAULT_GROUP

Support dynamic update of configuration

@SpringBootApplication
public class ConfigApplication {
    
    
    public static void main(String[] args) {
    
    
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigApplication.class, args);
        while(true){
    
    
        //当动态配置刷新时,会更新到 Enviroment中,因此这里每隔一秒中从Enviroment中获取配置
        String orderName = applicationContext.getEnvironment().getProperty("order.name");
        String num = applicationContext.getEnvironment().getProperty("order.num");
        System.out.println("order name :" + orderName + "; num: " + num);
        TimeUnit.SECONDS.sleep(1);
        }
    }
}

ps: In addition to the default configuration file, other dataId must be suffixed

The Nacos client defaults to a Properties type configuration. If you want to use yml, you need the following configuration

spring:
  application:
    name: com.zmz.order
  cloud:
    nacos:
      server-addr: 192.168.13.1:8848
      username: nacos
      password: nacos
      config:
        namespace: public
        file-extension: yaml
     #   refresh-enabled: false   客户端将无法感知配置的变化
        
#Nacos客户端默认是Properties类型的配置如果想使用yml需要 file-extension: yaml(只针对默认配置文件和profile格式配置文件,可以自定义配置文件)

1.3.1 Support profile granular configuration

(Different environments have different configuration files such as application-dev.yml)

server:
  port: 8050
spring:
  profiles:
    active: dev

When springcloudstarteralibabanacosconfig loads the configuration, it not only loads spring . application . name . {spring.application.name} named with dataid.s pr in g . a ppl i c a t i o n . nam e . {file-extension:properties} is the basic configuration of the prefixspring . application . name − {spring.application.nameis also loaded.}-s p r in g . a ppl i c a t i o n . nam e {profile}.${file-extension:properties} basic configuration** (except for the default configuration file, other configuration files must have a suffix )**. If you encounter different configurations in multiple environments during daily development, you can configure it through the ${spring.profiles.active} configuration item provided by Spring.

However, only the default configuration file (the configuration file with the same dataId as the service name) can use profile granular configuration.

Example:

Create a -dev configuration file

There will be a priority for the configuration file to take effect (the one with a higher priority will override the one with a lower priority and be complementary), provided that the specified file-extension: yaml configuration file suffix is ​​removed.

profile>default profile>custom profile

1.3.2 Support namespace classification configuration (according to environment regulations)

Support custom namespace configuration

Used for tenant-granular configuration isolation. Configurations of the same Group or Data ID can exist in different namespaces. One of the common scenarios of Namespace is the isolation and differentiation of configurations in different environments, such as the isolation of resources (such as configurations and services) between development and testing environments and production environments.

Just modify config.namespace directly to the specified namespace id .

 spring.cloud.nacos.config.namespace=8f46651d-94f6-4697-8054-8bc25b815165

1.3.3 Support custom Group configuration (by project category)

Group is one of the dimensions of organizational configuration. Group configuration sets by a meaningful string (such as Buy or Trade) to distinguish configuration sets with the same Data ID. When you create a configuration on Nacos, if the name of the configuration group is not filled in, the name of the configuration group defaults to DEFAULT_GROUP. Common scenarios for configuration grouping: Different applications or components use the same configuration type, such as database_url configuration and MQ_topic configuration. In the absence of an explicit ${spring.cloud.nacos.config.group} configuration, the default is DEFAULT_GROUP. If you need to customize your own Group, you can do so through the following configuration:

spring.cloud.nacos.config.group= GROUP_ZMZ

1.3.4 Support custom extended Data Id configuration

Data ID is one of the dimensions by which an organization divides its configuration. Data IDs are often used to organize configuration sets that divide a system. A system or application can contain multiple configuration sets, and each configuration set can be identified by a meaningful name. Data ID usually uses the naming rules of Java-like packages (such as com.taobao.tc.refund.log.level) to ensure global uniqueness. This naming rule is optional.

  • Modify application test
@SpringBootApplication
public class ConfigApplication {
    
    
    public static void main(String[] args) {
    
    
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigApplication.class, args);
        String orderName = applicationContext.getEnvironment().getProperty("order.name");
        String num = applicationContext.getEnvironment().getProperty("order.num");
        String userConfig = applicationContext.getEnvironment().getProperty("user.config");
        System.out.println("order name :" + orderName + "; num: " + num);
        System.out.println("userConfig :" + userConfig);
    }
}
  • Modify yaml
spring:
  application:
    name: com.zmz.order
  cloud:
    nacos:
      server-addr: 192.168.13.1:8848
      username: nacos
      password: nacos
      config:
        namespace: public
        #        namespace: 8f46651d-94f6-4697-8054-8bc25b815165
        file-extension: yaml
        #   refresh-enabled: false   客户端将无法感知配置的变化

        group: DEFAULT_GROUP
        shared-configs:
          - data-id: com.zdy.common.properties
            refresh: true
        extension-configs:
          - data-id: com.extension.common.properties
            refresh: true
#Nacos客户端默认是Properties类型的配置如果想使用yml需要 file-extension: yaml(只针对默认配置文件和profile格式配置文件,可以自定义配置文件)
#除了默认的配置文件,其他配置文件必须写上后缀
#profile>默认配置文件>自定义配置文件( extension-configs:>shared-configs,在下表越大优先级越大)

1.3.5 @RefreshScope

The @Value annotation can obtain the value of the configuration center, but the modified value cannot be dynamically sensed. You need to use the @RefreshScope annotation.

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
    
    
    @Value("${user.name}")
    public String userName;

    @RequestMapping("/show")
    public String show() {
    
    
        return userName;
    }
}

Guess you like

Origin blog.csdn.net/qq_45925197/article/details/129654483