Nacos Config集成SpringCloud使用说明

简介: Nacos config提供了配置中心的解决方案,且功能非常的强大适用,提供单机与集群模式系统集成的方式maven包依赖 <dependency> <groupId>org.

Nacos config提供了配置中心的解决方案,且功能非常的强大适用,提供单机与集群模式

  • 系统集成的方式
  1. maven包依赖
    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>0.2.1.RELEASE</version>
    </dependency>

    2.bootstrap.properties配置文件

#nacos配置中心地址
spring.cloud.nacos.config.server-addr=10.136.15.122:8848
#默认应用名称,配置中心中data-id 默认为name+file-extension
spring.application.name=example
没有配置情况下用name作为前缀
#spring.cloud.nacos.config.prefix
#应用文件格式支持properties,yml两种
spring.cloud.nacos.config.file-extension=properties

3.java应用代码

package com.nacos;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

    @Value("${useLocalCache:false}")
    private boolean useLocalCache;
    
    /**
     * http://localhost:8080/config/get
     */
    @RequestMapping("/get")
    public boolean get() {
        return useLocalCache;
    }
}
package com.nacos;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigApplication.class, args);
    }
}

4.启动应用,nacos配置中心配置参数,访问/config/get 结果为true ,结果配置成功

  • 参数配置说明 
#配置中心地址
spring.cloud.nacos.config.server-addr=10.136.15.122:8848

#应用名称,非必须,如果没有配置prefix,默认以name为前缀
#spring.application.name=example
#data-id前缀
spring.cloud.nacos.config.prefix=example
#文件类型,支持properties和yml两种数据格式
spring.cloud.nacos.config.file-extension=properties
#环境,可以隔离不同配置环境之间的配置,如dev,uat,pro
spring.profiles.active=dev
#命名空间 也是起隔离作用的,隔离不同应用这之间的作用
spring.cloud.nacos.config.namespace=c04b0cdf-91c7-470a-b6a9-423da6cc7a2b

#分组起隔离同一命名空间下,不同的分组
spring.cloud.nacos.config.group=test

#加载额外配置,除加载上面主配置文件外,额外加载的公有配置功能
spring.cloud.nacos.config.ext-config[0].data-id=test.properties
spring.cloud.nacos.config.ext-config[0].refresh=true

  
  • 部分源码解析

     NacosPropertySourceLocator类是Nacos Config的核心执行类,实现了PropertySourceLocator接口,在SpringCloud项目启动中就会加载执行的类,具体如下

   PropertySourceBootstrapConfiguration 是SpringCloud下的配置类实现了ApplicationContextInitializer接口,执行init方法,具本原因可以查询ApplicationContextInitializer相关接口的文档说明,代码如下

public void initialize(ConfigurableApplicationContext applicationContext) {
        CompositePropertySource composite = new CompositePropertySource(
                BOOTSTRAP_PROPERTY_SOURCE_NAME);
        AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
        boolean empty = true;
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        for (PropertySourceLocator locator : this.propertySourceLocators) {
            PropertySource<?> source = null;
            source = locator.locate(environment);
            if (source == null) {
                continue;
            }
            logger.info("Located property source: " + source);
            composite.addPropertySource(source);
            empty = false;
        }
        if (!empty) {
            MutablePropertySources propertySources = environment.getPropertySources();
            String logConfig = environment.resolvePlaceholders("${logging.config:}");
            LogFile logFile = LogFile.get(environment);
            if (propertySources.contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
                propertySources.remove(BOOTSTRAP_PROPERTY_SOURCE_NAME);
            }
            insertPropertySources(propertySources, composite);
            reinitializeLoggingSystem(environment, logConfig, logFile);
            setLogLevels(applicationContext, environment);
            handleIncludedProfiles(environment);
        }
}

发现最终执行的locate方法,我们查看下NacosPropertySourceLocator的locate的实现如下

public PropertySource<?> locate(Environment env) {

        ConfigService configService = nacosConfigProperties.configServiceInstance();

        if (null == configService) {
            LOGGER.warn(
                    "no instance of config service found, can't load config from nacos");
            return null;
        }
        long timeout = nacosConfigProperties.getTimeout();
        nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
                timeout);
        String name = nacosConfigProperties.getName();
       /*配置的分组*/
        String nacosGroup = nacosConfigProperties.getGroup();
        /*配置的前缀*/
        String dataIdPrefix = nacosConfigProperties.getPrefix();
        if (StringUtils.isEmpty(dataIdPrefix)) {
            dataIdPrefix = name;
        }

        /*前缀没有,则取spring.application.name*/
        if (StringUtils.isEmpty(dataIdPrefix)) {
            dataIdPrefix = env.getProperty("spring.application.name");
        }

        List<String> profiles = Arrays.asList(env.getActiveProfiles());
        nacosConfigProperties.setActiveProfiles(profiles.toArray(new String[0]));

        String fileExtension = nacosConfigProperties.getFileExtension();

        CompositePropertySource composite = new CompositePropertySource(
                NACOS_PROPERTY_SOURCE_NAME);
        
        loadSharedConfiguration(composite);
        loadExtConfiguration(composite);
        /*加载配置方法*/
        loadApplicationConfiguration(composite, nacosGroup, dataIdPrefix, fileExtension);

        return composite;
}

通过这个方法,大概能明白我们上面的一些配置的作用,下面再看下loadApplicationConfiguration 加载配置的方法,loadSharedConfiguration,loadExtConfiguration是加载扩展配置的方式,这里就详细说明了

private void loadApplicationConfiguration(
            CompositePropertySource compositePropertySource, String nacosGroup,
            String dataIdPrefix, String fileExtension) {
        loadNacosDataIfPresent(compositePropertySource,
                dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true);
        for (String profile : nacosConfigProperties.getActiveProfiles()) {
            String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
            loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
                    fileExtension, true);
        }
}

这里可以看到,会优先加载dateIdPrefix+DOT+fileExtension的配置,而后在加载环境的配置从而覆盖之前的配置,这就是上面配置dev的作用

    private void loadNacosDataIfPresent(final CompositePropertySource composite,
            final String dataId, final String group, String fileExtension,
            boolean isRefreshable) {
        if (NacosContextRefresher.loadCount.get() != 0) {
            NacosPropertySource ps;
            if (!isRefreshable) {
                ps = NacosPropertySourceRepository.getNacosPropertySource(dataId);
            }
            else {
                ps = nacosPropertySourceBuilder.build(dataId, group, fileExtension, true);
            }

            composite.addFirstPropertySource(ps);
        }
        else {
            NacosPropertySource ps = nacosPropertySourceBuilder.build(dataId, group,
                    fileExtension, isRefreshable);
            composite.addFirstPropertySource(ps);
        }
    }

再往下就是拉取配置中心的数据的过程,就不看下去了

相关文章
|
9月前
|
JSON Java Nacos
SpringCloud 应用 Nacos 配置中心注解
在 Spring Cloud 应用中可以非常低成本地集成 Nacos 实现配置动态刷新,在应用程序代码中通过 Spring 官方的注解 @Value 和 @ConfigurationProperties,引用 Spring enviroment 上下文中的属性值,这种用法的最大优点是无代码层面侵入性,但也存在诸多限制,为了解决问题,提升应用接入 Nacos 配置中心的易用性,Spring Cloud Alibaba 发布一套全新的 Nacos 配置中心的注解。
874 143
|
10月前
|
存储 Java Nacos
Spring Cloud+Nacos+KMS 动态配置最佳实践
本文讲述了 Spring Cloud 应用中结合 Nacos 实现了运行期配置动态更新的功能,以及在此基础上结合 KMS 在不改动代码的情况下对应用使用的敏感配置进行保护,解决将配置迁移到 Nacos 中可能存在的数据安全顾虑,并对其底层工作原理做了简单介绍。
1261 155
|
7月前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
2900 14
|
Cloud Native Java Nacos
微服务时代的新宠儿!Spring Cloud Nacos实战指南,带你玩转服务发现与配置管理,拥抱云原生潮流!
【8月更文挑战第29天】Spring Cloud Nacos作为微服务架构中的新兴之星,凭借其轻量、高效的特点,迅速成为服务发现、配置管理和治理的首选方案。Nacos(命名和配置服务)由阿里巴巴开源,为云原生应用提供了动态服务发现及配置管理等功能,简化了服务间的调用与依赖管理。本文将指导你通过五个步骤在Spring Boot项目中集成Nacos,实现服务注册、发现及配置动态管理,从而轻松搭建出高效的微服务环境。
569 0
|
8月前
|
监控 Java Nacos
使用Spring Boot集成Nacos
通过上述步骤,Spring Boot应用可以成功集成Nacos,利用Nacos的服务发现和配置管理功能来提升微服务架构的灵活性和可维护性。通过这种集成,开发者可以更高效地管理和部署微服务。
2299 17
|
11月前
|
JSON SpringCloudAlibaba Java
Springcloud Alibaba + jdk17+nacos 项目实践
本文基于 `Springcloud Alibaba + JDK17 + Nacos2.x` 介绍了一个微服务项目的搭建过程,包括项目依赖、配置文件、开发实践中的新特性(如文本块、NPE增强、模式匹配)以及常见的问题和解决方案。通过本文,读者可以了解如何高效地搭建和开发微服务项目,并解决一些常见的开发难题。项目代码已上传至 Gitee,欢迎交流学习。
834 1
Springcloud Alibaba + jdk17+nacos 项目实践
|
负载均衡 Java Nacos
SpringCloud基础2——Nacos配置、Feign、Gateway
nacos配置管理、Feign远程调用、Gateway服务网关
SpringCloud基础2——Nacos配置、Feign、Gateway
|
负载均衡 Java Nacos
SpringCloud基础1——远程调用、Eureka,Nacos注册中心、Ribbon负载均衡
微服务介绍、SpringCloud、服务拆分和远程调用、Eureka注册中心、Ribbon负载均衡、Nacos注册中心
SpringCloud基础1——远程调用、Eureka,Nacos注册中心、Ribbon负载均衡
|
11月前
|
负载均衡 算法 Java
蚂蚁面试:Nacos、Sentinel了解吗?Springcloud 核心底层原理,你知道多少?
40岁老架构师尼恩分享了关于SpringCloud核心组件的底层原理,特别是针对蚂蚁集团面试中常见的面试题进行了详细解析。内容涵盖了Nacos注册中心的AP/CP模式、Distro和Raft分布式协议、Sentinel的高可用组件、负载均衡组件的实现原理等。尼恩强调了系统化学习的重要性,推荐了《尼恩Java面试宝典PDF》等资料,帮助读者更好地准备面试,提高技术实力,最终实现“offer自由”。更多技术资料和指导,可关注公众号【技术自由圈】获取。
蚂蚁面试:Nacos、Sentinel了解吗?Springcloud 核心底层原理,你知道多少?
|
Cloud Native Java Nacos
Spring Cloud Config、Apollo、Nacos和Archaius对比
这篇文章对比了Spring Cloud Config、Apollo、Nacos和Archaius这四种配置中心的适应场景、优缺点。文中讨论了它们的功能特点,例如Spring Cloud Config的集中化配置管理和动态刷新能力,Apollo的实时配置推送和权限治理,Nacos的服务发现和管理功能,以及Archaius的动态配置更新能力。文章指出选择配置中心应根据项目需求和架构来决定,并提供了一个对比图来帮助读者更直观地理解这些工具的差异。
442 1
Spring Cloud Config、Apollo、Nacos和Archaius对比