[关闭]
@aloxc 2019-11-11T11:18:16.000000Z 字数 4159 阅读 3883

springboot如何获取nacos中的配置文件

springboot nacos


如题,我们在使用springcloud的时候直接在maven中添加依赖

  1. <dependency>
  2. <groupId>com.alibaba.boot</groupId>
  3. <artifactId>nacos-config-spring-boot-starter</artifactId>
  4. <version>${latest.version}</version>
  5. </dependency>

并且在springboot的配置文件(application.yml)中添加nacos的地址相关配置

  1. spring:
  2. application:
  3. name: dict
  4. cloud:
  5. nacos:
  6. config:
  7. server-addr: 172.16.5.112:9002
  8. shared-dataids: common.yml,${spring.application.name}.yml
  9. refreshable-dataids: common.yml,${spring.application.name}.yml
  10. namespace:
  11. discovery:
  12. server-addr: 172.16.5.112:9002
  13. namespace:
  14. main:
  15. allow-bean-definition-overriding: true

做完这两部就可以使用nacos作为springboot的配置中心和注册中心了。
我们在代码中想使用配置文件中的某个配置直接使用类似下面代码即可

  1. @Value("${zkDevice.backuppath}")
  2. private String backuppath;

这是常规基本操作,nacos中还可以添加

TEXT
JSON
XML
YAML
HTML
Properties

这些类型的配置文件,当我们添加了一个什么文件的时候,我们想读取里面的内容如何办?注意,这个文件可能不是配置文件,比如说我添加了个abc.txt的文件,我们想读取里面的内容如何办?

我们先了解下springboot和nacos是如何集成的,从上面看出来,我们就添加了一点配置就可以使用nacos作为springcloud的注册中心和配置中心,那它是如何工作的?
先了解springboot如何加载远程配置的,springboot提供了加载远程配置的扩展接口,PropertySourceLocator。
那么也就是说nacos实现了其接口NacosPropertySourceLocator,从NacosPropertySourceLocator中我们可以看到这样一个属性private NacosPropertySourceBuilder nacosPropertySourceBuilder,该属性的类是用来读取配置的类,该类中有如下一些代码

  1. private Properties loadNacosData(String dataId, String group, String fileExtension) {
  2. String data = null;
  3. try {
  4. data = configService.getConfig(dataId, group, timeout);
  5. if (!StringUtils.isEmpty(data)) {
  6. log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
  7. dataId, group));
  8. if (fileExtension.equalsIgnoreCase("properties")) {
  9. Properties properties = new Properties();
  10. properties.load(new StringReader(data));
  11. return properties;
  12. }
  13. else if (fileExtension.equalsIgnoreCase("yaml")
  14. || fileExtension.equalsIgnoreCase("yml")) {
  15. YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
  16. yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
  17. return yamlFactory.getObject();
  18. }
  19. }
  20. }
  21. catch (NacosException e) {
  22. log.error("get data from Nacos error,dataId:{}, ", dataId, e);
  23. }
  24. catch (Exception e) {
  25. log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
  26. }
  27. return EMPTY_PROPERTIES;
  28. }

该方法读取出来的都是都是yaml或者properties这样的配置,我们其实是想读取某个文本文件,怎么办?该方法中有如下代码 configService.getConfig(dataId, group, timeout);,这个就是读取文件的代码。知道这些逻辑后,整理出一个类,如下(NacosConfig.java),nacos里面有些类的属性是private,使用反射方法读取里面的数据!

  1. import com.alibaba.nacos.api.exception.NacosException;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceBuilder;
  5. import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
  6. import org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration;
  7. import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
  8. import org.springframework.context.ConfigurableApplicationContext;
  9. import org.springframework.stereotype.Component;
  10. import java.lang.reflect.Field;
  11. import java.util.List;
  12. /**
  13. * nacos工具类
  14. * @author liyh
  15. */
  16. @Component
  17. @Slf4j
  18. public class NacosConfig {
  19. @Autowired
  20. private PropertySourceBootstrapConfiguration propertySourceBootstrapConfiguration;
  21. /**
  22. * 从nacos中读取某个配置文件的内容
  23. * @param group 对应到nacos中的group组
  24. * @param dataId 对应到nacos中的dataId
  25. * @param timeout
  26. * @return
  27. */
  28. public String getData(String group,String dataId,long timeout){
  29. try {
  30. Field propertySourceLocators = PropertySourceBootstrapConfiguration.class.getDeclaredField("propertySourceLocators");
  31. propertySourceLocators.setAccessible(true);
  32. List<PropertySourceLocator> list = (List<PropertySourceLocator>)propertySourceLocators.get(propertySourceBootstrapConfiguration);
  33. NacosPropertySourceLocator nacosLocator = null;
  34. for(PropertySourceLocator locator : list){
  35. if(locator instanceof NacosPropertySourceLocator){
  36. nacosLocator = (NacosPropertySourceLocator)locator;
  37. }
  38. }
  39. if(nacosLocator == null){
  40. return null;
  41. }
  42. Field nacosPropertySourceBuilderField = NacosPropertySourceLocator.class.getDeclaredField("nacosPropertySourceBuilder");
  43. nacosPropertySourceBuilderField.setAccessible(true);
  44. NacosPropertySourceBuilder nacosPropertySourceBuilder = (NacosPropertySourceBuilder)nacosPropertySourceBuilderField.get(nacosLocator);
  45. String config = nacosPropertySourceBuilder.getConfigService().getConfig(dataId, group, timeout);
  46. return config;
  47. } catch (NoSuchFieldException | IllegalAccessException | NacosException e) {
  48. log.error("nacos工具异常",e);
  49. }
  50. return null;
  51. }
  52. }

此处输入图片的描述

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注