大家好,我是小悟。
一、Nacos 详细介绍
1.1 什么是 Nacos
Nacos (Dynamic Naming and Configuration Service)是阿里巴巴开源的一款集服务发现 、配置管理 和服务管理 于一体的平台。Nacos 的名字来源于 Na ming and Co nfiguration Service 的缩写。
1.2 Nacos 的核心特性
1.2.1 服务发现与服务健康监测
- 服务注册:微服务启动时自动向 Nacos 注册自己的实例信息
- 服务发现:服务消费者可以从 Nacos 获取可用的服务实例列表
- 健康检查:支持 TCP/HTTP 健康检查,自动剔除不健康实例
- 负载均衡:内置权重管理和流量控制策略
1.2.2 动态配置管理
- 配置集中管理:所有环境配置集中存储在 Nacos 中
- 动态刷新:支持配置的动态刷新,无需重启应用
- 多环境支持:支持命名空间(Namespace)隔离不同环境
- 版本管理:配置的版本管理和一键回滚
- 监听查询:实时监听配置变化并通知客户端
1.2.3 动态 DNS 服务
- 支持权重路由
- 更易于实现自定义负载均衡策略
- 支持路由规则灵活调整
1.2.4 服务及其元数据管理
- 服务元数据管理
- 服务端点管理
- 服务生命周期管理
1.3 Nacos 的架构优势
- 易用性:提供简单的 UI 控制台,易于操作
- 高可用:支持集群部署,保证高可用性
- 可扩展:插件化设计,易于扩展功能
- 多语言支持:支持 Java、Go、Python 等多种语言
- 与 Spring Cloud 生态完美集成:无缝替代 Eureka、Config 等组件
二、Spring Cloud 集成 Nacos 详细步骤
2.1 环境准备
2.1.1 Nacos Server 安装
# 下载 Nacos Server(以 2.2.3 版本为例)
wget https://github.com/alibaba/nacos/releases/download/2.2.3/nacos-server-2.2.3.tar.gz
# 解压
tar -zxvf nacos-server-2.2.3.tar.gz
# 启动(单机模式)
cd nacos/bin
sh startup.sh -m standalone
# 访问控制台
# http://localhost:8848/nacos
# 默认账号/密码:nacos/nacos
2.2 创建 Spring Boot 项目
2.2.1 Maven 父工程 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-cloud-nacos-demo</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud 依赖管理 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba 依赖管理 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>nacos-provider</module>
<module>nacos-consumer</module>
<module>nacos-config</module>
<module>nacos-gateway</module>
</modules>
</project>
2.3 服务注册与发现
2.3.1 服务提供者(Provider)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-nacos-demo</artifactId>
<groupId>com.example</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-provider</artifactId>
<dependencies>
<!-- Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 健康检查 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 8081
spring:
application:
name: nacos-provider-service
cloud:
nacos:
discovery:
# Nacos Server 地址
server-addr: localhost:8848
# 命名空间,用于环境隔离(默认public)
namespace: public
# 分组(默认DEFAULT_GROUP)
group: DEFAULT_GROUP
# 集群名称
cluster-name: BJ
# 服务注册的IP
ip: 127.0.0.1
# 服务注册的端口
port: 8081
# 元数据
metadata:
version: 1.0
author: example
# 是否启用Nacos
enabled: true
# 健康检查配置
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
启动类 ProviderApplication.java
package com.example.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
@RestController
class ProviderController {
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return String.format("Hello %s, this is nacos provider!", name);
}
@GetMapping("/health")
public String health() {
return "Provider service is healthy!";
}
}
2.3.2 服务消费者(Consumer)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-nacos-demo</artifactId>
<groupId>com.example</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- OpenFeign 服务调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- LoadBalancer 负载均衡 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 8082
spring:
application:
name: nacos-consumer-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: public
group: DEFAULT_GROUP
# 启用 LoadBalancer
spring.cloud.loadbalancer.ribbon.enabled: false
# Feign 配置
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
启动类 ConsumerApplication.java
package com.example.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@Bean
@LoadBalanced // 启用负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
class ConsumerController {
private final RestTemplate restTemplate;
private final ProviderFeignClient providerFeignClient;
public ConsumerController(RestTemplate restTemplate,
ProviderFeignClient providerFeignClient) {
this.restTemplate = restTemplate;
this.providerFeignClient = providerFeignClient;
}
// 使用 RestTemplate 调用
@GetMapping("/call/rest/{name}")
public String callByRestTemplate(@PathVariable String name) {
String url = "http://nacos-provider-service/hello/" + name;
return restTemplate.getForObject(url, String.class);
}
// 使用 Feign 调用
@GetMapping("/call/feign/{name}")
public String callByFeign(@PathVariable String name) {
return providerFeignClient.hello(name);
}
}
// Feign 客户端接口
@org.springframework.cloud.openfeign.FeignClient(
value = "nacos-provider-service",
path = "/"
)
interface ProviderFeignClient {
@GetMapping("/hello/{name}")
String hello(@PathVariable String name);
@GetMapping("/health")
String health();
}
2.4 配置中心集成
2.4.1 配置管理模块
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-nacos-demo</artifactId>
<groupId>com.example</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-config</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Nacos 配置管理 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- Nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 配置刷新 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
bootstrap.yml(配置文件优先级高于 application.yml)
# bootstrap.yml
spring:
application:
name: nacos-config-service
profiles:
active: dev
cloud:
nacos:
config:
# Nacos Server 地址
server-addr: localhost:8848
# 配置文件后缀
file-extension: yaml
# 命名空间(环境隔离)
namespace: dev
# 分组
group: DEFAULT_GROUP
# 共享配置
shared-configs:
- data-id: common.yaml
group: DEFAULT_GROUP
refresh: true
# 扩展配置
extension-configs:
- data-id: ext.yaml
group: DEFAULT_GROUP
refresh: true
discovery:
server-addr: localhost:8848
namespace: dev
# 配置刷新端点
management:
endpoints:
web:
exposure:
include: refresh,health,info
在 Nacos 控制台创建配置:
-
Data ID :
nacos-config-service-dev.yaml -
Group :
DEFAULT_GROUP -
配置格式 :
YAML -
配置内容:
应用配置
app:
name: nacos-config-demo
version: 1.0.0
description: Nacos配置中心示例数据库配置
database:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.DriverRedis配置
redis:
host: 127.0.0.1
port: 6379
timeout: 3000
database: 0业务配置
business:
enabled: true
max-connections: 100
timeout: 5000
retry-count: 3
配置管理类 ConfigApplication.java
package com.example.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
@RestController
@RefreshScope // 支持配置动态刷新
class ConfigController {
@Value("${app.name:default}")
private String appName;
@Value("${app.version:1.0.0}")
private String appVersion;
@Value("${database.url:default-url}")
private String dbUrl;
@Value("${business.enabled:false}")
private boolean businessEnabled;
@Value("${business.max-connections:10}")
private int maxConnections;
@GetMapping("/config")
public String getConfig() {
return String.format(
"App: %s v%s | DB: %s | Business Enabled: %s | Max Connections: %d",
appName, appVersion, dbUrl, businessEnabled, maxConnections
);
}
@GetMapping("/refresh")
public String refresh() {
return "Configuration refreshed! Current config: " + getConfig();
}
}
// 使用 @ConfigurationProperties 绑定配置
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "business")
@RefreshScope
public class BusinessProperties {
private boolean enabled;
private int maxConnections;
private int timeout;
private int retryCount;
// Getter和Setter方法
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public int getMaxConnections() { return maxConnections; }
public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; }
public int getTimeout() { return timeout; }
public void setTimeout(int timeout) { this.timeout = timeout; }
public int getRetryCount() { return retryCount; }
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
@Override
public String toString() {
return String.format(
"BusinessProperties{enabled=%s, maxConnections=%d, timeout=%d, retryCount=%d}",
enabled, maxConnections, timeout, retryCount
);
}
}
2.5 使用 Spring Cloud Gateway 集成 Nacos
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-nacos-demo</artifactId>
<groupId>com.example</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-gateway</artifactId>
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Nacos 配置中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 8080
spring:
application:
name: nacos-gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: public
group: DEFAULT_GROUP
gateway:
discovery:
locator:
enabled: true # 启用服务发现
lower-case-service-id: true
routes:
- id: provider-service
uri: lb://nacos-provider-service
predicates:
- Path=/provider/**
filters:
- StripPrefix=1
- AddRequestHeader=X-Request-Foo, Bar
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
key-resolver: "#{@pathKeyResolver}"
- id: consumer-service
uri: lb://nacos-consumer-service
predicates:
- Path=/consumer/**
filters:
- StripPrefix=1
- id: config-service
uri: lb://nacos-config-service
predicates:
- Path=/config/**
filters:
- StripPrefix=1
网关配置类 GatewayApplication.java
package com.example.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public KeyResolver pathKeyResolver() {
return exchange -> Mono.just(
exchange.getRequest().getPath().value()
);
}
}
2.6 Nacos 集群部署配置(可选)
cluster.conf 配置
properties
# Nacos 集群节点配置
192.168.1.101:8848
192.168.1.102:8848
192.168.1.103:8848
application.properties 配置
properties
# 集群模式
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=123456
三、详细总结
3.1 集成优势
3.1.1 一站式解决方案
Nacos 提供了服务发现 和配置管理的统一平台,避免了使用多个独立组件(如 Eureka + Config + Bus)带来的复杂性和维护成本。
3.1.2 高性能与高可用
- 服务发现:基于 Raft 协议,保证数据一致性
- 配置管理:基于 Derby/MySQL 存储,支持集群部署
- 健康检查:支持 TCP/HTTP/MYSQL 多种健康检查方式
3.1.3 易于使用和运维
- 提供友好的 Web 控制台
- 完整的 RESTful API
- 丰富的监控指标
3.2 最佳实践建议
3.2.1 命名空间规划
# 建议按环境划分命名空间
namespace:
dev: 开发环境
test: 测试环境
pre: 预发环境
prod: 生产环境
3.2.2 配置管理策略
- 配置分类存储 :
- 公共配置:使用
shared-configs - 应用配置:按应用独立存储
- 环境配置:使用不同命名空间
- 公共配置:使用
- 配置版本控制 :
- 重要配置变更前进行备份
- 使用配置历史版本功能
- 建立配置变更审核机制
3.2.3 服务治理
- 权重管理:根据服务器性能设置不同权重
- 元数据管理:利用 metadata 存储版本、区域等信息
- 集群容灾:配置多个集群,实现容灾切换
3.3 注意事项
3.3.1 网络与安全
- 生产环境建议使用内网域名访问
- 启用 Nacos 的认证功能
- 配置合适的网络策略和防火墙规则
3.3.2 监控与告警
- 监控 Nacos Server 的 CPU、内存、磁盘使用率
- 设置服务实例数异常告警
- 监控配置变更频率
3.3.3 容量规划
- 根据服务实例数量规划 Nacos 集群规模
- 定期清理无效的服务实例
- 监控配置数量,避免配置过多影响性能
3.4 故障排查指南
3.4.1 常见问题
- 服务注册失败 :
- 检查网络连通性
- 验证 Nacos Server 状态
- 检查命名空间和分组配置
- 配置无法刷新 :
- 确认
@RefreshScope注解已添加 - 检查配置 Data ID 和 Group 是否正确
- 验证应用是否有读取配置的权限
- 确认
- 服务发现异常 :
- 检查健康检查配置
- 验证负载均衡策略
- 查看服务实例元数据
3.4.2 日志分析
- Nacos Server 日志:
logs/nacos.log - 客户端日志:设置
logging.level.com.alibaba.cloud.nacos=DEBUG - 网关日志:启用 Gateway 的详细日志
3.5 性能优化建议
-
客户端配置优化:
spring:
cloud:
nacos:
discovery:
# 心跳间隔(默认5秒)
heart-beat-interval: 5000
# 心跳超时(默认15秒)
heart-beat-timeout: 15000
# 实例刷新间隔(默认30秒)
instance-poll-interval: 30000 -
服务端优化 :
- 根据实例数量调整 JVM 参数
- 使用 MySQL 替代内嵌数据库
- 配置合适的集群节点数量
3.6 扩展功能
3.6.1 配置监听
@NacosConfigListener(dataId = "nacos-config-service-dev.yaml")
public void onMessage(String config) {
log.info("Config changed: {}", config);
// 处理配置变更逻辑
}
3.6.2 服务事件监听
@Component
public class ServiceChangeListener {
@EventListener
public void onInstanceChange(NamingEvent event) {
log.info("Service {} instances changed: {}",
event.getServiceName(),
event.getInstances());
}
}
3.7 迁移建议
从传统的 Spring Cloud Netflix 组件迁移到 Nacos:
- Eureka → Nacos Discovery:无缝迁移,只需更改依赖和配置
- Config + Bus → Nacos Config:简化架构,减少组件依赖
- Ribbon → Nacos + LoadBalancer:更灵活的服务路由
3.8 最后
Nacos 作为云原生时代的服务基础设施,正在持续演进:
- 更好的 Kubernetes 集成
- 更强大的服务治理能力
- 更完善的可观测性支持
- 多语言 SDK 的持续丰富
通过 Spring Cloud Alibaba Nacos 的集成,可以获得一个功能完整、性能优异、易于运维的微服务基础设施平台,大大降低了微服务架构的复杂度和维护成本。

谢谢你看我的文章,既然看到这里了,如果觉得不错,随手点个赞、转发、在看三连吧,感谢感谢。那我们,下次再见。
您的一键三连,是我更新的最大动力,谢谢
山水有相逢,来日皆可期,谢谢阅读,我们再会
我手中的金箍棒,上能通天,下能探海