本文共 1773 字,大约阅读时间需要 5 分钟。
在代码的模块服务中安装Nacos配置依赖。可以通过以下Maven依赖添加到项目中:
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config
在Nacos配置中心中进行服务配置,注意区分服务名称和模块名。服务名称即在bootstrap.yaml中配置的服务名称。
在模块的bootstrap.yml文件中添加以下配置:
spring.cloud.nacos.config: server-addr: 127.0.0.1:8848 file-extension: yaml group: DEFAULT_GROUP ext-config[0]: data-id: ext-config-common01.yaml group: COMMON_GROUP refresh: true ext-config[1]: data-id: ext-config-common02.yaml group: COMMON_GROUP refresh: true
使用@Value注解获取配置信息。例如:
@Value("${common.name}")private String common_name;@GetMapping(value = "/configs")public String getValue() { return applicationContext.getEnvironment().getProperty("common.name");} 在Nacos中添加两个拓展配置文件:
在bootstrap.yml中添加以下配置:
config: server-addr: 127.0.0.1:8848 file-extension: yaml group: DEFAULT_GROUP ext-config[0]: data-id: ext-config-common01.yaml group: COMMON_GROUP refresh: true ext-config[1]: data-id: ext-config-common02.yaml group: COMMON_GROUP refresh: true
在需要获取动态配置的类中注入ConfigurableApplicationContext,并使用以下方法获取配置:
@Autowiredprivate ConfigurableApplicationContext applicationContext;@GetMapping(value = "/config")public String getValue() { String name = applicationContext.getEnvironment().getProperty("common.name"); String addr = applicationContext.getEnvironment().getProperty("common.addr"); return name + addr;} 根据配置,服务会返回合并的配置信息,确保主配置优先,拓展配置按下标排序。
通过以上步骤,可以有效地配置和使用Nacos,实现动态配置管理和扩展配置。
转载地址:http://ewcfk.baihongyu.com/