springboot reads nacos configuration center configuration

Official address: https://nacos.io/zh-cn/docs/quick-start-spring-boot.html

Example:

The content of the project is as follows:

One, nacos edit configuration file

  • dataId:cloud.service-platform.media
  • Group:service-platform
  • The configuration format is useless, just add a little color for easy editing
  • Configured a port8081 and urlhead=test

  • namespace (tenat): The default namespace is public, you can add dev prod test (equivalent to the first layer of mutual isolation, each namespace has its own group)
  • group: The default group is DEFAULT_GROUP (group is equivalent to a specific scene)
  • dataid: equivalent to the file name is the service name by default (separate from each other under each group)

2. Client pom dependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.7</version>
        </dependency>

Three, configure application.properties

#nacos地址
nacos.config.server-addr=localhost:8848
#命名空间id
nacos.config.namespace=ns-dev
#用户名
nacos.config.username=nacos
#密码
nacos.config.password=nacos

You can also remove the application.properties configuration file and use the environment variable to obtain the configuration center address (the following two ways)

//此代码加载启动类中

//第二种方式    
    /**
     * 动态配置配置中心地址。全局NacosProperties
     * @return Properties
     */
    @Bean
    public Properties globalNacosProperties() {
        Properties properties = new Properties();
        //properties.setProperty("serverAddr",System.getProperty("serverAddr"));//从环境变量获取后放入Properties
        properties.setProperty("serverAddr","localhost:8848");
        properties.setProperty("username","nacos");
        properties.setProperty("namespace","ns-dev");
        properties.setProperty("password","nacos");
        return properties;
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }


//第三种方式
    public static void main(String[] args) {
        //设置环境变量
        System.setProperty("nacos.config.serverAddr","localhost:8848");
        System.setProperty("nacos.config.username","nacos");
        System.setProperty("nacos.config.namespace","ns-dev");
        System.setProperty("nacos.config.password","nacos");

        SpringApplication.run(DemoApplication.class,args);
        System.out.println("启动成功");
    }

Fourth, add @ NacosPropertySource annotation to the startup class

@SpringBootApplication
//设置配置源并开启自动更新
@NacosPropertySource(dataId = "cloud.service-platform.media",groupId = "service-platform",autoRefreshed = true)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Five, the controller takes the value through the @NacosValue annotation

@RestController
public class DemoController {

    //使用@value注解取值,它能取到值,但没有自动更新的功能
    @Value(value = "${urlhead}")
    private String urlhead;
    
    //使用@nacosValue注解获取值,并开启自动更新
    @NacosValue(value = "${urlhead}", autoRefreshed = true)
    private String urlheadAutoRefresh;

    @RequestMapping("/getValue")
    public String getValue() {
        System.out.println("urlhead:"+urlhead);
        System.out.println("urlheadAutoRefresh:"+urlheadAutoRefresh);
        return "";
    }
}

Six, test results

The result shows that @NacosValue can read the new value after the nacos configuration is modified. But @Value does not work.

 

The bottom of the client requests the location of nacos configuration:

Nacos is the configuration file information obtained through the get request of ClientWorker's getServerConfig method

 

Some vignettes that happened halfway

After inspection, it is found that the nacos client will use dataId as the file name. However, the client does not support configuration files with media suffixes

Through source code analysis, it is found that nacos only supports four configuration parsers:

So we can customize the class to implement the ConfigParse interface, and then add the class through SPI

Because my dataId suffix name does not meet the requirements, but the file content is still in the format of Properties, so we can directly inherit the DefaultPropertiesConfigParse class

//自定义类实现ConfigParse接口
public class DefaultMediaConfigParse extends DefaultPropertiesConfigParse {

    @Override
    public String processType() {
        return "media";
    }
}

SPI steps:

1. Create a two-layer META-INF/services/ folder under the classpath, add files inside, and the file name is the full class path name of the interface

Note: Do not create the META-INF.services folder directly on the idea, because only one layer is created

2. Add the full class path name of the implementation class to the file

Java spi mechanism reference: https://blog.csdn.net/sumengnan/article/details/113243995

 

Add custom parser to the source code of the collection

In the toProperties method of the ConfigParseUtils class, the custom configuration parser will be added to the properties collection of the default parser.

There are now five parsers, which can recognize and parse media files! !

 

That's it!
 

Guess you like

Origin blog.csdn.net/sumengnan/article/details/113247899