1.搭建服务
- 项目名:test-nacos-cloud-config
- 添加坐标
<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-config</artifactId>
</dependency>
</dependencies>
- 创建yml配置文件:bootstrap.yml
server:
port: 8072 # 端口号
spring:
application:
name: config-service # 服务名
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 # nacos 服务地址
prefix: ${spring.application.name} #data ID的前缀,默认服务名
file-extension: yaml # data ID的后缀:config-service.yaml
group: DEFAULT_GROUP # 组名
- 创建启动类
package com.czxy.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestNacosCloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(TestNacosCloudConfigApplication.class, args);
}
}
- 编写处理类:ConfigController
package com.czxy.nacos.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/config")
@RefreshScope //实现配置、实例热加载
public class ConfigController {
@Value("${czxy.message:'默认值'}")
private String msg;
/**
* http://localhost:8072/config/get
*/
@RequestMapping("/get")
public String get() {
return msg;
}
}
- 查询服务:浏览器访问 http://localhost:8072/config/get
- 访问,yml文件配置信息
czxy:
message: 测试数据
-
将配置信息放到yml文件中,重启服务
-
访问,nacos中的配置数据
-
nacos 配置文件加载顺序
1.bootstrap.yml
2.application.yml
3.application-[profile].yml
4.[serviceName].yml #nacos配置
5.[serviceName]-[profile].yml #nacos配置
后面加载的文件,将覆盖前面文件的配置内容