1、下载服务

https://github.com/alibaba/nacos/releases

2、报错及解决

报错:数据库未配置

  • java.lang.IllegalArgumentException: db.num is null
  • db.user or db.user.[index] is null
  • 解决:
    • 在本地创建nacos数据库
    • 进入/config中找到nacos-mysql.sql文件,在nacos中执行SQL
    • 找到application.properties文件修改配置
    • db.num=1
        spring.datasource.platform=mysql
        db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
        db.user=root
        db.password=123456
      

报错:java.net.UnknownHostException: jmenv.tbsite.net

  • 是启动模式没设置导致的:
    • sh startup.sh -m standalone
    • .\startup.cmd -m standalone

3、运行成功后

4、界面使用方法

4.1、新增配置

4.1.1、

wAUP54.png

4.1.2、

wAUtqf.png

4.1.3、

wAUadS.png

4.2、历史版本及回滚

wEufQe.png

4.3、查询某个 配置当前的被监听状态

wEuqW8.png

5、参数传递类型

配置文件

@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySources({
        @NacosPropertySource(dataId = "bst0", autoRefreshed = true,
                type = ConfigType.YAML,groupId = "TEST_GROUP"),
        @NacosPropertySource(dataId = "bst1", autoRefreshed = true,
                type = ConfigType.PROPERTIES,groupId = "TEST_GROUP")
})
public class NacosConfig {
  	@SuppressWarnings("InfiniteLoopStatement")
    @Override
    public void run(String... args) throws Exception {
        while (true) {
            Thread.sleep(4000);
        }
    }
}

5.1、YAML

image-20200905155113530

5.2、Properties

image-20200905155004471

5、SpringBoot集成Nacos

5.1、依赖

<!-- nacos 依赖 -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.7</version>
</dependency>

5.2、注意事项

==使用Nacos管理的配置项,在配置文件中不能存在,如果存在的话会导致Nacos的配置无法生效==

5.3、测试代码

5.3.1、配置类

/**
 * 添加 @EnableNacosConfig 注解启用 Nacos Spring 的配置管理服务,serverAddr配置nacos server地址
 * 使用 @NacosPropertySource 加载了 dataId 为 bst 的配置源,并启用自动刷新
 */
@Configuration
/**
 * dataId:这个属性是需要在Nacos中配置的DataId。
 * autoRefreshed:为true的话开启自动更新。
 */
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySources({
        @NacosPropertySource(dataId = "bst0", autoRefreshed = true,
                type = ConfigType.YAML,groupId = "TEST_GROUP"),
        @NacosPropertySource(dataId = "bst1", autoRefreshed = true,
                type = ConfigType.PROPERTIES,groupId = "TEST_GROUP")
})
public class NacosConfig {

}

5.3.2、Controller类

@Controller
public class NacosController {

    //${service.name:1}:默认值是1
    @NacosValue(value = "${service0:123}", autoRefreshed = true)
    private String service0;
    @NacosValue(value="${service1:123}",autoRefreshed = true)
    private String service1;

    @GetMapping("/test0")
    @ResponseBody
    public String testNacos0(){
        return service0;
    }

    @GetMapping("/test1")
    @ResponseBody
    public String testNacos1(){
        return service1;
    }
}