Nacos注册中心 #
一、Nacos概述 #
1.1 什么是Nacos #
Nacos(Dynamic Naming and Configuration Service)是阿里巴巴开源的服务发现和配置管理平台,提供了一站式的微服务治理解决方案。
text
┌─────────────────────────────────────────────────────────────┐
│ Nacos核心功能 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ 服务注册与发现 │ │ 动态配置管理 │ │
│ │ Service Registry │ │ Config Management │ │
│ │ │ │ │ │
│ │ - 服务注册 │ │ - 配置存储 │ │
│ │ - 服务发现 │ │ - 配置推送 │ │
│ │ - 健康检查 │ │ - 配置监听 │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Nacos Console │ │
│ │ (管理控制台) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
1.2 Nacos特性 #
| 特性 | 说明 |
|---|---|
| 服务发现 | 支持DNS和RPC服务发现 |
| 动态配置 | 配置实时推送 |
| 动态DNS | 支持权重路由 |
| 服务健康 | 多种健康检查方式 |
| 多语言 | 支持Java、Go、Node.js等 |
1.3 Nacos vs Eureka #
| 特性 | Nacos | Eureka |
|---|---|---|
| CAP | AP/CP可切换 | AP |
| 配置中心 | ✅ | ❌ |
| 健康检查 | TCP/HTTP/MySQL | 心跳 |
| 雪崩保护 | ✅ | ✅ |
| 社区活跃度 | 活跃 | 维护模式 |
| 管理界面 | 完善 | 基础 |
二、安装部署 #
2.1 下载安装 #
bash
# 下载Nacos
wget https://github.com/alibaba/nacos/releases/download/2.3.0/nacos-server-2.3.0.tar.gz
# 解压
tar -xzf nacos-server-2.3.0.tar.gz
cd nacos/bin
2.2 单机模式启动 #
bash
# Linux/Mac
sh startup.sh -m standalone
# Windows
startup.cmd -m standalone
2.3 Docker部署 #
bash
# 单机模式
docker run -d \
--name nacos \
-e MODE=standalone \
-p 8848:8848 \
-p 9848:9848 \
-p 9849:9849 \
nacos/nacos-server:v2.3.0
2.4 访问控制台 #
访问 http://localhost:8848/nacos
默认账号密码:nacos/nacos
三、服务注册发现 #
3.1 添加依赖 #
xml
<dependencies>
<!-- Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3.2 配置文件 #
yaml
spring:
application:
name: service-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: public
group: DEFAULT_GROUP
service: ${spring.application.name}
weight: 1
metadata:
version: 1.0.0
region: default
server:
port: 8001
3.3 启动类 #
java
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
3.4 服务接口 #
java
@RestController
public class ProviderController {
@Value("${server.port}")
private String port;
@GetMapping("/hello")
public String hello() {
return "Hello from Nacos Provider, port: " + port;
}
}
四、服务调用 #
4.1 使用RestTemplate #
java
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
java
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consume")
public String consume() {
return restTemplate.getForObject(
"http://service-provider/hello",
String.class
);
}
}
4.2 使用OpenFeign #
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
java
@FeignClient("service-provider")
public interface ProviderClient {
@GetMapping("/hello")
String hello();
}
java
@RestController
public class ConsumerController {
@Autowired
private ProviderClient providerClient;
@GetMapping("/consume")
public String consume() {
return providerClient.hello();
}
}
五、命名空间与分组 #
5.1 命名空间 #
命名空间用于隔离不同环境的服务:
yaml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: dev
| 命名空间 | 说明 |
|---|---|
| public | 默认命名空间 |
| dev | 开发环境 |
| test | 测试环境 |
| prod | 生产环境 |
5.2 分组 #
分组用于同一环境下的服务分组:
yaml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: dev
group: ORDER_GROUP
5.3 创建命名空间 #
java
@RestController
public class NamespaceController {
@GetMapping("/create-namespace")
public String createNamespace() {
NamingService namingService = NamingFactory.createNamingService("localhost:8848");
namingService.registerInstance("service-provider", "192.168.1.100", 8001);
return "success";
}
}
六、集群部署 #
6.1 集群架构 #
text
┌─────────────────────────────────────────────────────────────┐
│ Nacos集群架构 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Nacos │ │ Nacos │ │ Nacos │ │
│ │ Node 1 │ │ Node 2 │ │ Node 3 │ │
│ │ :8848 │ │ :8849 │ │ :8850 │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ MySQL │ │
│ │ (数据存储) │ │
│ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
6.2 配置MySQL #
创建数据库 nacos,执行 conf/mysql-schema.sql
6.3 集群配置 #
修改 conf/cluster.conf:
text
192.168.1.100:8848
192.168.1.101:8848
192.168.1.102:8848
修改 conf/application.properties:
properties
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=nacos
db.password.0=nacos
6.4 启动集群 #
bash
# 各节点启动
sh startup.sh
6.5 Nginx负载均衡 #
nginx
upstream nacos-cluster {
server 192.168.1.100:8848;
server 192.168.1.101:8848;
server 192.168.1.102:8848;
}
server {
listen 8848;
server_name localhost;
location /nacos/ {
proxy_pass http://nacos-cluster/nacos/;
}
}
七、健康检查 #
7.1 健康检查配置 #
yaml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
heart-beat-interval: 5000
heart-beat-timeout: 15000
ip-delete-timeout: 30000
7.2 健康检查类型 #
| 类型 | 说明 |
|---|---|
| TCP | TCP端口检查 |
| HTTP | HTTP接口检查 |
| MySQL | MySQL连接检查 |
7.3 自定义健康检查 #
java
@RestController
public class HealthController {
@GetMapping("/health")
public Map<String, Object> health() {
Map<String, Object> health = new HashMap<>();
health.put("status", "UP");
health.put("timestamp", System.currentTimeMillis());
return health;
}
}
八、服务权重 #
8.1 配置权重 #
yaml
spring:
cloud:
nacos:
discovery:
weight: 0.5
8.2 动态调整权重 #
在Nacos控制台调整服务实例权重,或通过API:
java
@RestController
public class WeightController {
@GetMapping("/set-weight")
public String setWeight(
@RequestParam String serviceName,
@RequestParam String ip,
@RequestParam int port,
@RequestParam double weight) throws NacosException {
NamingService namingService = NamingFactory.createNamingService("localhost:8848");
namingService.instance(serviceName, ip, port).setWeight(weight);
return "success";
}
}
九、配置详解 #
9.1 完整配置 #
yaml
spring:
application:
name: service-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: public
group: DEFAULT_GROUP
service: ${spring.application.name}
weight: 1
cluster-name: DEFAULT
metadata:
version: 1.0.0
region: default
heart-beat-interval: 5000
heart-beat-timeout: 15000
ip-delete-timeout: 30000
register-enabled: true
enabled: true
ephemeral: true
ip:
port:
network-interface:
ip-type: IPv4
9.2 配置项说明 #
| 配置项 | 默认值 | 说明 |
|---|---|---|
| server-addr | localhost:8848 | Nacos服务地址 |
| namespace | public | 命名空间 |
| group | DEFAULT_GROUP | 分组 |
| service | $ | 服务名 |
| weight | 1 | 权重 |
| heart-beat-interval | 5000 | 心跳间隔 |
| heart-beat-timeout | 15000 | 心跳超时 |
| ip-delete-timeout | 30000 | IP删除超时 |
十、最佳实践 #
10.1 生产环境配置 #
yaml
spring:
application:
name: service-provider
cloud:
nacos:
discovery:
server-addr: ${NACOS_SERVER_ADDR:nacos1:8848,nacos2:8848,nacos3:8848}
namespace: ${NACOS_NAMESPACE:prod}
group: ${NACOS_GROUP:DEFAULT_GROUP}
service: ${spring.application.name}
weight: 1
metadata:
version: @project.version@
region: ${REGION:default}
heart-beat-interval: 5000
heart-beat-timeout: 15000
ip-delete-timeout: 30000
ephemeral: true
server:
port: ${PORT:8001}
10.2 注意事项 #
| 注意点 | 说明 |
|---|---|
| 集群部署 | 至少3个节点 |
| 数据持久化 | 使用MySQL存储 |
| 网络隔离 | 使用命名空间隔离环境 |
| 监控告警 | 配置服务健康监控 |
十一、总结 #
11.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 服务注册 | 自动注册到Nacos |
| 服务发现 | 从Nacos获取服务列表 |
| 命名空间 | 环境隔离 |
| 分组 | 服务分组管理 |
| 集群 | 高可用部署 |
11.2 下一步 #
现在你已经掌握了Nacos注册中心的使用,接下来让我们学习 Consul注册中心,了解HashiCorp的服务发现方案!
最后更新:2026-03-28