首页 > 编程语言 > 详细

springcloud项目配置拓展从本地config目录加载

时间:2019-08-27 18:49:17      阅读:83      评论:0      收藏:0      [点我收藏+]

本文受阿里开源的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);

}

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

具体请看我分享的git库https://github.com/lyg123/SpringCloudLocalCofigDemo

新的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目录加载

原文:https://www.cnblogs.com/li-yg/p/11419732.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!