目标
演示 Spring Boot 应用接入 Nacos,实现服务注册发现 + 动态配置热更新。启动两个实例后,通过 Nacos 控制台修改配置,应用无需重启即可生效。
完整代码
1. pom.xml 依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2023.0.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2023.0.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. bootstrap.yml
spring:
application:
name: demo-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: public
group: DEFAULT_GROUP
config:
server-addr: 127.0.0.1:8848
namespace: public
group: DEFAULT_GROUP
file-extension: yaml
refresh-enabled: true
3. 动态配置类
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class ConfigController {
@Value("${app.message:Hello Nacos!}")
private String message;
@Value("${app.feature.enabled:false}")
private boolean featureEnabled;
@GetMapping("/config")
public String getConfig() {
return String.format("message=%s, featureEnabled=%s", message, featureEnabled);
}
}
4. 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5. Nacos 控制台配置
在 Nacos 控制台 配置管理 → 配置列表 中新建配置:
- Data ID:
demo-service.yaml
- Group:
DEFAULT_GROUP
- 配置内容:
app:
message: "Hello from Nacos Config!"
feature:
enabled: true
运行步骤
cd nacos/bin &
mvn spring-boot:run
mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8081
curl http:
curl http:
curl http:
预期输出
{"hosts":[{"ip":"192.168.1.5","port":8080,"healthy":true},
{"ip":"192.168.1.5","port":8081,"healthy":true}]}
message=Hello from Nacos Config!, featureEnabled=true
message=New value from Nacos!, featureEnabled=true
关键点
@RefreshScope 实现配置热更新,无需重启应用
- Data ID 命名规则:
${spring.application.name}.${file-extension}
- Nacos 服务列表实时反映实例上下线,支持主动健康检查
- 可结合
@NacosValue 注解实现更细粒度的配置注入