在spring cloud
体系中,有很多的注册中心和配置中心,比如最早的eureka
以及consul
、ZooKeeper
,配置中心有
spring cloud config
及 携程的apollo config
,今天我们要说的是阿里新秀Nacos
来作为配置中心或者注册中心
Nacos是什么
Nacos is committed to help you discover, configure, and manage your microservices. It provides a set of simple and useful features enabling you to realize dynamic service discovery, service configuration, service metadata and traffic management.
Nacos makes it easier and faster to construct, deliver and manage your microservices platform. It is the infrastructure that supports a service-centered modern application architecture with a microservices or cloud-native approach.
Nacos 致力于帮助您发现、配置和管理微服务.Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理.
Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台. Nacos 是构建以服务
为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施.
准备
安装Nacos server
动手能力强的小伙伴可以尝试自己编译,需要提前配置Java
及Maven
|
|
启动Nacos server
Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式):
|
|
如果您使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:
|
|
Windows
|
|
你也可以直接双击startup.cmd
运行
如何在spring cloud 中使用
作为配置中心使用
引入依赖
为了方便管理Spring cloud
及nacos
版本,可以提前在父级项目中配置dependencyManagement
|
|
|
|
配置nacos server
application.yml
中添加spring.application.name
及spring.cloud.nacos.server-addr
|
|
spring.application.name
是组成nacos 配置管理dataId
字段的一部分spring.cloud.nacos.server-addr
nacos 的地址- 完整的
dataId
在spring cloud nacos
中为${prefix}-${spring.profile.active}.${file-extension}
prefix
默认为spring.application.name
的值,也可以通过配置项spring.cloud.nacos.config.prefix
来配置.spring.profile.active
即为当前环境对应的profile
,详情可以参考 Spring Boot文档. 注意:当spring.profile.active
为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成${prefix}.${file-extension}
file-exetension
为配置内容的数据格式,可以通过配置项spring.cloud.nacos.config.file-extension
来配置.目前只支持properties
和yaml
类型,默认为properties
编写启动类
|
|
编写Controller
|
|
添加配置
- 访问
http://localhost:8848/nacos/
用户名密码nacos
- 点击左侧菜单
配置管理>配置列表
,在右侧点击+
添加配置 - 在输入页填写
Data ID
为我们配置的spring.application.name
- 配置格式选择为
Properties
,在配置内容添加nacosConfig=hello
如果Data ID
填写错误,是无法获取到对应配置的
添加完成后,返回到配置管理,可以看到我们刚刚添加的配置
启动项目
访问http://localhost:8080/config
,此时页面输出hello
,那么恭喜你,大功告成.
作为服务的注册中心使用
添加依赖
添加spring-cloud-starter-alibaba-nacos-discovery
实现服务的注册和发现
|
|
启动项目
此时,我们到nacos
左侧菜单中点击服务管理>服务列表
,可以看到我们刚刚启动的服务已经成功注册到了列表中
Nacos config 解读
那么,nacos是如何获取到配置在nacos server的配置的呢
查看源码我们可以看到在spring-cloud-starter-alibaba-nacos-config
模块中,nacos添加了com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration
的自启动,
其中NacosConfigProperties
就是获取配置的关键,
|
|
|
|
|
|
|
|
获取配置关键
curl get http://config-server:{port}/v1/cs/configs?dataId={dataId}&group={group}&tenant={tenant}
|
|
好啦,今天就说到这里,如有疑问可以评论区留言