一、操作Naocs
1、创建命名空间 JYR_DEV
2、在JYR_DEV命名空间下,创建配置文件myconfig.yaml
二、新建springboot项目,加入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>Greenwich.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
三、加入项目配置文件bootstrap.yaml
server:
port: 6001
spring:
application:
name: myconfig
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 #配置中心地址
file-extension: yaml
namespace: 8fa92f2f-4ca9-4458-a62f-90d3252395c3 #xxx命名空间
group: JYR_GROUP #xxx组
四、编写MyController类
@RestController
public class MyController {
//方式一:这种方式缺点是,当配置文件在nacos中修改时,这儿不会动态更新
@Value("${project_name.name}")
private String config1;
@GetMapping("/getconfig1")
public String getConfig1(){
return config1;
}
//方式二:这种方式优点是,当配置文件在nacos中修改时,这儿会动态更新
@Autowired
private ConfigurableApplicationContext configurableApplicationContext;
@GetMapping("/getconfig2")
public String getConfig2(){
return configurableApplicationContext.getEnvironment().getProperty("project_name.name");
}
五、访问测试
localhost:8080/getconfig1