springBoot 配置nacos 遇到的问题
本地的nacos server端用的是1.4.1版本(因为偷懒, 所以踩坑)
根据官网文档的教程
1.增加依赖 <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-config-spring-boot-starter</artifactId> <version>教程未指定具体版本</version> </dependency>
2.增加配置文件属性 nacos.config.server-addr=127.0.0.1:8848
3.是使用2个注解, 实现了动态配置的效果
@NacosPropertySource(dataId = "example", autoRefreshed = true) @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
由于idea提示的最新版为 0.2.10 就直接使用了, 用如下代码, 获取 dataId配置的内容
参考github的代码 https://github.com/nacos-group/nacos-spring-project try { String serverAddr = "127.0.0.1:8848"; String dataId = "自定义的dataId"; String group = "DEFAULT_GROUP"; Properties properties = new Properties(); properties.put("serverAddr", serverAddr); ConfigService configService = NacosFactory.createConfigService(properties); String content = configService.getConfig(dataId, group, 5000); System.out.println(content); } catch (NacosException e) { e.printStackTrace(); }
但是发现配置没获取到
直接启动springBoot项目, 发现启动日志上面输出 NacosConfigApplicationContextInitializer : [Nacos Config Boot] : The preload configuration is not enabled
尝试手动开启 nacos.config.bootstrap.enable=true 出现了空指针, 查看相关类却少参数 type nacos.config.type=yml 到这一步加载还是有问题 There is no content for NacosPropertySource from dataId
本来只是打算简单试一下, 此时感觉太对劲 最终在别人的文章中发现版本 nacos-config-spring-boot-starter 0.2.1 是正常的
在好奇心的趋势下 查看了下对应的 nacos-client的版本 nacos-config-spring-boot-starter 0.2.8以下, nacos-client 是1.x的版本 nacos-config-spring-boot-starter 0.2.9开始, nacos-client 是2.X的版本
赶紧下载了 2.X的 nacos server端, 再次尝试, 就正常了
总结: 虽然官网教程没有直接的给出版本号, 但也要注意client 和 server版本的一致
=============================== 另外: 搭建nacos server端 可以使用 阿里云 知行动手实验室 (需要登陆)
教程很详细的介绍了nacos的使用