Nacos 是啥
Nacos 可以用来做服务发现和配置中心
这里暂时使用 Nacos 做配置中心。
Nacos 控制台页面
Nacos 地址:http://127.0.0.1:8848/nacos/
账户名:admin
密码:123456
接入方法
本地开发环境配置 Nacos 域名解析,hosts 中添加
127.0.0.1 nacos
原来Maven项目的父项目集成了 Spring-Cloud-Config,启动时会自己去拉取配置,所以这个要改掉。
把原来的父项目换成
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent>
加入对应的 Spring Cloud 的版本管理配置
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>0.2.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
增加 Nacos 的 jar 包
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
bootstrap.yml 中的配置如下
spring: profiles: active: @phase@ cloud: nacos: config: server-addr: nacos:8848 file-extension: yaml # 他大爷的,命名空间的这个也要加上,文档上完全没有啊,这个地方真的是血坑 namespace: 1470b864-9acc-42c0-8e0b-40ad39bc0c5a # 组名也要加上啊 group: DEFAULT_GROUP application: name: @project.name@
解释:
- nacos 会去找
${prefix}-${spring.profiles.active}.${file-extension}
的配置文件 prefix
默认为spring.application.name
的值,也可以通过配置项spring.cloud.nacos.config.prefix
来配置。spring.profiles.active
即为当前环境对应的 profile, 注意:当 spring.profile.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成${prefix}.${file-extension}
file-exetension
为配置内容的数据格式,可以通过配置项spring.cloud.nacos.config.file-extension
来配置。目前只支持properties
和yaml
类型。- 目前按照我这个配置就可以了
- nacos 会去找
把自己的配置从 git 上复制过来,并在控制台中 JUGGLE 空间中创建属于自己的配置,注意,配置文件中不能出现中文,补充,其实可以出现中文,之前报错是因为 IDEA 的项目文件编码是 GBK,要改成 UTF-8 就可以了。
续
按照如上配置项目可以顺利启动,此外 Nacos 还可以做热更新,实时推送配置。其他特性自己探索。