Nacos作为配置中心

Nacos可作为consul config作为配置中心,Nacos 是支持热加载的.

下面介绍springboot如何集成nacos作为配置中心
1、添加依赖

 <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.1</version>
        </dependency>

注意:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。

2、在 application.properties 中配置 Nacos server 的地址:

spring.application.name=springboot2-nacos-config
nacos.config.server-addr=127.0.0.1:8848
server.port=8088

3、使用 @NacosPropertySource 加载 dataId 为 springboot2-nacos-config 的配置源,并开启自动更新

@SpringBootApplication
@RestController
@NacosPropertySource(dataId = "springboot2-nacos-config", autoRefreshed = true)
@RefreshScope
public class NacosApplication {

    public static void main(String[] args) {

        SpringApplication.run(NacosApplication.class, args);
    }

4、通过 Nacos 的 @NacosValue 注解设置属性值。

@NacosValue(value = "${nacos.test.propertie:123}",autoRefreshed = true)
    private String testProperties;

5、启动 NacosConfigApplication,调用:http://localhost:8088/test,返回内容是 123.

 @GetMapping("/test")
    public String test() {
        return testProperties;
    }

6、在nacos的控制台http://127.0.0.1:8848/nacos/index.html.修改配置
在这里插入图片描述
7、再次调用:http://localhost:8088/test.可以看到返回的结果为098.配置被动态更新了.


版权声明:本文为weixin_41709748原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。