本文受阿里开源的Nacos启发,应用启动后从Nacos服务加载配置到应用中,想着本地开发的时候加载配置能否从本地存储中加载,这样也能加快开发效率

首先

我们来看下SpringCloud项目应用Nacos服务的bootstrap.yaml配置如下

spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
discovery:
server-addr: 127.0.0.1:8848
application:
name: demo
profiles:
active: db,redis,rabbit,es,zk

然后在Nacos控制台加配置

经过如上之后,这样应用就能从Nacos取配置。

问题点

笔者认为这里开发的时候如果能从文件系统中加载配置替代Nacos,能加快开发效率,也能心情舒畅的Coding业务代码了。

解决思路

分析

经过分析启动配置spring.factories和配置类NacosConfigProperties

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.alibaba.nacos.NacosConfigBootstrapConfiguration

找到NacosConfigBootstrapConfiguration 代码如下

@Configuration
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigBootstrapConfiguration { @Bean
@ConditionalOnMissingBean
public NacosConfigProperties nacosConfigProperties() {
return new NacosConfigProperties();
} @Bean
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
} }

里面关键是NacosPropertySourceLocator 实现的接口PropertySourceLocator

/**
* Strategy for locating (possibly remote) property sources for the Environment.
* Implementations should not fail unless they intend to prevent the application from
* starting.
*
* @author Dave Syer
*
*/
public interface PropertySourceLocator { /**
* @param environment The current Environment.
* @return A PropertySource, or null if there is none.
* @throws IllegalStateException if there is a fail-fast condition.
*/
PropertySource<?> locate(Environment environment); }

到了这里就明白怎么做了。

实现

定义自己的应用启动配置类MyLocalConfigBootstrapConfiguration

@Configuration
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", havingValue = "false")
public class MyLocalConfigBootstrapConfiguration { @Bean
public MyLocalPropertySourceLocator fyLocalPropertySourceLocator() {
return new MyLocalPropertySourceLocator();
}
}

定义META-INF/spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.liyghting.core.MyLocalConfigBootstrapConfiguration

定义自己的配置加载器MyLocalPropertySourceLocator

@Order(0)
public class MyLocalPropertySourceLocator implements PropertySourceLocator {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyLocalPropertySourceLocator.class);
private static final String MYLOCAL_PROPERTY_SOURCE_NAME = "MYLOCAL"; @Override
public PropertySource<?> locate(Environment environment) { CompositePropertySource composite = new CompositePropertySource(
MYLOCAL_PROPERTY_SOURCE_NAME);
String dataIdPrefix = environment.getProperty("spring.application.name");
String fileExtension = ".yaml";
PropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader(); URL baseClassesUrl = this.getClass().getClassLoader().getResource("");
File baseClassesFile = new File(baseClassesUrl.getFile());
String basePath = baseClassesFile.getParentFile().getParentFile().getAbsolutePath(); Resource resource = new FileSystemResource(basePath + "/config/" + dataIdPrefix + fileExtension);
try {
composite.addFirstPropertySource(propertySourceLoader.load(dataIdPrefix + fileExtension, resource).get(0));
} catch (IOException e) {
LOGGER.warn("can not load property source {}, exception: {}", dataIdPrefix + fileExtension, e);
}
for (String activeProfile : environment.getActiveProfiles()) {
try {
resource = resource.createRelative(dataIdPrefix + "-" + activeProfile + fileExtension);
composite.addFirstPropertySource(propertySourceLoader.load(dataIdPrefix + "-" + activeProfile + fileExtension, resource).get(0));
} catch (IOException e) {
LOGGER.warn("can not load property source {}, exception: {}", dataIdPrefix + "-" + activeProfile + fileExtension, e);
}
} return composite;
}
}

版本信息spring-boot 2.1.6.RELEASE

spring-cloud Greenwich.SR2

spring-cloud-alibaba 0.9.0.RELEASE

具体请看我分享的git库

新的bootstarp.yaml配置如下

spring:
cloud:
nacos:
config:
enabled: false
server-addr: 127.0.0.1:8848
file-extension: yaml
discovery:
server-addr: 127.0.0.1:8848
application:
name: demo
profiles:
active: db,redis,rabbit,es,zk

这样应用启动配置能从本地文件系统加载或Nacos服务加载

springcloud项目配置拓展从本地config目录加载的更多相关文章

  1. ruby -- 进阶学习(十一)配置解决production环境下无法加载css或js

    最近配置production环境,找了好几份文档,从傻逼到苦逼~~终于配置成功~~@_@!!! 首先,先加载以下几个插件: # Use Uglifier as compressor for JavaS ...

  2. django 项目运行时static静态文件不能加载问题处理

    一.首先检查网页中的加载路径是否正确,如果和文件所在路径不一致,就把html改下路径 二.加载路径和文件实际路径一致,看下配置文件: STATIC_URL = '/static/'STATIC_ROO ...

  3. 配置Spring的用于解决懒加载问题的过滤器

    <?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" ...

  4. Bean 注解(Annotation)配置(1)- 通过注解加载Bean

    Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...

  5. Prism 学习:从本地目录加载 Module

    在 Prism 中,将外部模块加载到主程序有以下几种方式:Code.XAML.配置文件.指定模块目录:其中,如果要使用 Code 方式来加载 Module,则需要将该 Module 引用到当前项目中: ...

  6. 【.NET】VS 本地调试 无法加载Json文件

    1.如果要是发布到iis,还加载不出来,那就要配置一下MIME类型: 2.本地调试时,无法加载json文件: 解决方案: 在web.config中添加如下配置:mimeMap <system.w ...

  7. 创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或

    C:\Users\xxx\Documents\IISExpress\config\applicationhost.config 将这里面带的项目路径替换成你当前路径 {"创建 caching ...

  8. scrapy项目5:爬取ajax形式加载的数据,并用ImagePipeline保存图片

    1.目标分析: 我们想要获取的数据为如下图: 1).每本书的名称 2).每本书的价格 3).每本书的简介 2.网页分析: 网站url:http://e.dangdang.com/list-WY1-dd ...

  9. SSM项目使用junit单元测试时Mybaties通配符加载Mapper不能正常加载

    个人博客 地址:http://www.wenhaofan.com/article/20181108104133 问题描述 项目使用maven build 以及tomcat run能够正常运行,但是使用 ...

随机推荐

  1. 2019年7月19日 - LeetCode0001

    https://leetcode-cn.com/problems/two-sum/ 我的方法: class Solution { public int[] twoSum(int[] nums, int ...

  2. 在vue中创建自定义指令

    原文:https://dev.to/ratracegrad/creating-custom-directives-in-vue-58hh 翻译:心上有杨 指令是带有 v- 前缀的特殊属性.指令的作用是 ...

  3. 简单粗暴的方式解决eclipse下安装STS失败的问题

    直接去Spring官网下载,spring定制eclipse https://spring.io/tools

  4. 【iOS】iOS CocoaPods 整理

    github 上下载 Demo 时第一次遇到这个情况,当时有些不知所措,也没怎么在意,后来项目调整结构时正式见到了这个,并且自己去了解学习了. CocoaPods安装和使用教程 这篇文章写得很好!ma ...

  5. 解决:django.db.utils.OperationalError: unable to open database file

    这是一个从GitHub上下载的,一个网站项目的源码.想要在自己的电脑上运行,期间过程相当曲折,不过至此终于是完成了. 1.安装过程: python2->virtualenv->django ...

  6. Model设计中常见的技巧和注意事项

    verbose_name 可以作为第一个参数传入,书写更加工整和有序: name = models.CharField('类别名',default="", max_length=3 ...

  7. cogs 264. 数列操作 单点修改 区间查询

    http://cogs.pro:8080/cogs/problem/problem.php?pid=pyNimmVeq 264. 数列操作 ★☆   输入文件:shulie.in   输出文件:shu ...

  8. MobaXterm:远程终端登录软件封神选手

    提到SSH.Telnet等远程终端登录,我相信很多人想到的都是PuTTY PuTTY通常用于Windows,但实际上可以多平台运行,因此不表达为"Windows下的远程终端登录" ...

  9. React 如何搭建脚手架

    React 如何搭建脚手架   npm install -g create-react-app    //安装 create-react-app react-demo    // react-demo ...

  10. mui的app页面使用layui填充数据

    在mui的开发中有个坑,mui.plusReady在web上使用时是不会起作用的,只能在app上才行,所以推荐自己测试时使用mui.ready去写加载时的方法. 前端请求的返回格式为json,所以在后 ...