
大家好,我是小悟。
Nacos(Dynamic Naming and Configuration Service)是阿里巴巴开源的一款集服务发现、配置管理和服务管理于一体的平台。Nacos 的名字来源于 Naming and Configuration Service 的缩写。
# 下载 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<?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>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!";
}
}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();
}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 控制台创建配置:
nacos-config-service-dev.yamlDEFAULT_GROUPYAML# 应用配置
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.Driver
# Redis配置
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
);
}
}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()
);
}
}cluster.conf 配置
properties
# Nacos 集群节点配置
192.168.1.101:8848
192.168.1.102:8848
192.168.1.103:8848application.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=123456Nacos 提供了服务发现和配置管理的统一平台,避免了使用多个独立组件(如 Eureka + Config + Bus)带来的复杂性和维护成本。
# 建议按环境划分命名空间
namespace:
dev: 开发环境
test: 测试环境
pre: 预发环境
prod: 生产环境shared-configs@RefreshScope 注解已添加logs/nacos.loglogging.level.com.alibaba.cloud.nacos=DEBUGspring:
cloud:
nacos:
discovery:
# 心跳间隔(默认5秒)
heart-beat-interval: 5000
# 心跳超时(默认15秒)
heart-beat-timeout: 15000
# 实例刷新间隔(默认30秒)
instance-poll-interval: 30000@NacosConfigListener(dataId = "nacos-config-service-dev.yaml")
public void onMessage(String config) {
log.info("Config changed: {}", config);
// 处理配置变更逻辑
}@Component
public class ServiceChangeListener {
@EventListener
public void onInstanceChange(NamingEvent event) {
log.info("Service {} instances changed: {}",
event.getServiceName(),
event.getInstances());
}
}从传统的 Spring Cloud Netflix 组件迁移到 Nacos:
Nacos 作为云原生时代的服务基础设施,正在持续演进:
通过 Spring Cloud Alibaba Nacos 的集成,可以获得一个功能完整、性能优异、易于运维的微服务基础设施平台,大大降低了微服务架构的复杂度和维护成本。

谢谢你看我的文章,既然看到这里了,如果觉得不错,随手点个赞、转发、在看三连吧,感谢感谢。那我们,下次再见。
您的一键三连,是我更新的最大动力,谢谢
山水有相逢,来日皆可期,谢谢阅读,我们再会
我手中的金箍棒,上能通天,下能探海
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。