spring cloud 使用nacos配置中心
创建NACOS配置
- Data ID: 配置文件名,格式为 <spring.cloud.nacos.config.prefix>[-spring.profiles.active].<spring.cloud.nacos.config.file-extension>
- Group: 分组,<spring.cloud.nacos.config.group>
依赖
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置
bootstrap.yml
spring:
application:
name: sample-nacos1
profiles:
active: dev
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
# 默认前缀为${spring.application.name}
prefix: ${spring.application.name}
# 默认配置文件扩展名为properties
file-extension: yml
# 默认名空间为public
namespace: public
# 默认组为DEFAULT_GROUP
group: SAMPLE_NACOS
效果
日志显示找到了配置文件
b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-sample-nacos1-dev.yml,SAMPLE_NACOS'}, BootstrapPropertySource {name='bootstrapProperties-sample-nacos1.yml,SAMPLE_NACOS'}, BootstrapPropertySource {name='bootstrapProperties-sample-nacos1,SAMPLE_NACOS'}]
注意
- spring.cloud.nacos.config.namespace配置如果使用自定义命名空间,需要填入命名空间ID而非名称
- 启动报错org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1
可能出现在不同环境部署启动报此错误情况,是JVM默认字符集问题导致,设置启动JVM参数 -Dfile.encoding=UTF-8即可