一、Nacos 介绍
Nacos = Na ming + Co nfiguration + Service
阿里巴巴开源的注册中心 和配置中心组件
🎯 核心功能
-
服务发现与注册 (Naming Service)
-
动态配置管理 (Configuration Service)
-
服务健康监测
-
动态DNS服务
📦 依赖坐标
<!-- 服务注册与发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 配置中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
二、安装与启动
1. 安装步骤
# 1. 上传并解压
cd /usr/upload
tar -zxvf nacos-server-1.4.1.tar.gz -C /usr/local
# 2. 启动(单机模式)
cd /usr/local/nacos/bin
./startup.sh -m standalone
# 3. 关闭
./shutdown.sh
2. 访问测试
-
地址:
http://192.168.61.132:8848/nacos -
账号:
nacos/nacos
三、Nacos 作为注册中心
🔧 服务提供者 (Provider)
application.yml
spring:
application:
name: nacos-provider
cloud:
nacos:
discovery:
server-addr: 192.168.61.132:8848
启动类
@SpringBootApplication
@EnableDiscoveryClient // 开启服务发现
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
🔧 服务消费者 (Consumer)
Controller示例
@RestController
public class ConsumerController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/getUserById/{id}")
public User getUserById(@PathVariable Integer id) {
// 1. 获取服务实例
List<ServiceInstance> instances =
discoveryClient.getInstances("nacos-provider");
ServiceInstance instance = instances.get(0);
// 2. 拼接URL
String url = String.format("http://%s:%s/provider/getUserById/%s",
instance.getHost(),
instance.getPort(),
id);
// 3. 调用服务
return restTemplate.getForObject(url, User.class);
}
}
四、Nacos 作为配置中心
1. 基础配置
bootstrap.yml (优先级高于application.yml)
spring:
cloud:
nacos:
config:
server-addr: 192.168.61.132:8848
prefix: nacos-config # 配置前缀
file-extension: yaml # 配置文件后缀
application:
name: nacos-config-service # 服务名称
2. 配置管理规则
Data Id 命名规则:
${prefix}-${spring.profiles.active}.${file-extension}
或
${prefix}.${file-extension}(无profile时)
示例:nacos-config-dev.yaml
3. 动态刷新
@RestController
@RefreshScope // 支持配置动态刷新
public class ConfigController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/config")
public String getConfig() {
return configInfo;
}
}
🎯 核心概念补充
1. 命名空间 (Namespace)
-
用于多环境/多租户隔离
-
默认:
public
2. 配置分组 (Group)
-
默认:
DEFAULT_GROUP -
可对不同服务/不同模块进行分组
3. 配置优先级
bootstrap.yml > 远程配置 > application.yml
4. 配置示例(Nacos控制台)
# Data Id: nacos-config.yaml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
custom:
config: hello-nacos
💡 最佳实践建议
-
多环境配置
# 开发环境 spring: profiles: dev # 生产环境 spring: profiles: prod -
共享配置
- 使用
shared-configs或extension-configs共享通用配置
- 使用
-
服务治理
-
结合Ribbon/OpenFeign实现负载均衡
-
设置服务权重、元数据等
-
-
健康检查
-
支持TCP/HTTP/MySQL健康检查
-
自动剔除不健康实例
-