概念
Nacos是阿里巴巴的产品,现在是springcloud的一个组件,相比于Eureka更加丰富。
启动 (单机启动)
进入nacos\bin目录,cmd进入控制台,输入startup.cmd -m standalone

浏览器输入地址:http://192.168.0.101:8848/nacos/index.html#/login
默认账号密码均为:nacos

springboot中添加nacos
添加依赖
父工程的pom.xml添加依赖:
xml
<!-- nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

子工程客户端添加依赖:
xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

修改子工程中的application.yml文件
yaml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848

启动测试

分级存储模型
- 一级是服务,例如userservice
- 二级是集群,例如地点上海或者杭州
- 三级是机房,例如杭州的机房部署了userservice服务器
对于同一集群的服务器,消费者会优先调用同一集群的生产者服务器,若同一集群的生产者服务器宕机,则调用其他集群的服务器。
如何修改
在application.xml文件,添加spring.cloud.nacos.discovery.cluster-name属性


查看


负载均衡
设置
修改消费者的apllication.yml,设置Rule
(生产者为userservice,消费者为orderservice)
yaml
userservice:
ribbon:
NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule
NacosRule 策略:
- 优先选择同一集群的服务者实例
- 本地集群找不到,才回去其他集群查找
- 确定好服务者实例后,采用随机选择

相关策略:

权重控制
若权重设为0,理论上消费者不会调用该生产者,那么即使是在白天,也可以进行服务器的升级

环境隔离

复制命名空间id:24a1cb4c-91be-4177-a914-1fbdd4f898c1

application.yml 中添加 namespace: 24a1cb4c-91be-4177-a914-1fbdd4f898c1


热部署
nacoss上新建配置

文本框内容按照自己需求编写

客户端导入依赖
xml
<dependency>
<groupId>com.alibaba.cloud </groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
从application.yml中抽取需要单独修改的配置,bootstrap的优先级高于application

法一:添加注解
@RefreshScope + @Value("${pattern.deteformat}")

法二:方法中注入


多环境配置共享
优先级:服务名-profile.yaml > 服务名.yaml > 本地配置
如: userservice-dev.yaml > userservice.yaml > application.yaml