0


Spring Cloud集成Nacos实现本地配置优先 | Spring Cloud 9

一、前言

Nacos Config Starter

实现了

org.springframework.cloud.bootstrap.config.PropertySourceLocator

接口,并将优先级设置为最高。

Spring Cloud

应用启动阶段,会主动从

Nacos Server

端获取对应的数据,并将获取到的数据转换成

PropertySource

且注入到

Environment

PropertySources

属性中,所以使用

@Value

注解也能直接获取

Nacos Server

端配置的内容。

二、本地配置覆盖远程配置

前言部分已说明

Nacos Config Starter

将远程配置优先级设置成为最高,故需要在远程配置中心(nacos)上设置本地配置覆盖远程配置

在远程的

${prefix}-${spring.profiles.active}.${file-extension}

中配置以下部分:

spring:cloud:config:# 如果本地配置优先级高,那么 override-none 设置为 true,包括系统环境变量、本地配置文件等配置override-none:true# 如果想要远程配置优先级高,那么 allow-override 设置为 false,如果想要本地配置优先级高那么 allow-override 设置为 trueallow-override:true# 只有系统环境变量或者系统属性才能覆盖远程配置文件的配置,本地配置文件中配置优先级低于远程配置;注意本地配置文件不是系统属性override-system-properties:false

针对部分属性无本地化配置,则根据上篇文章Spring Cloud融合Nacos配置加载优先级 | Spring Cloud 8中描述的配置加载优先级进行互补汇总。

三、测试

在远程配置中心

nacos

服务端中新增以下配置:
在这里插入图片描述
本地配置

bootstrap-dev.yml
config:name: bootstrap-dev

本地配置

bootstrap.yml
server:port:3001spring:profiles:active: dev
  application:name: @artifactId@
  cloud:nacos:username: @nacos.username@
      password: @nacos.password@
      config:server-addr: 192.168.0.31:8848prefix: @artifactId@
        file-extension: yaml
        # 用于共享的配置文件shared-configs:-data-id: common-mysql.yaml
            group: DEFAULT_GROUP
            refresh:true-data-id: common-redis.yaml
            group: DEFAULT_GROUP
            refresh:true-data-id: common-base.yaml
            group: DEFAULT_GROUP
            refresh:true# 用于扩展的配置文件# extension-configs 优先级大于 shared-configs,在 shared-configs 之后加载extension-configs:-data-id: @[email protected]
            group: DEFAULT_GROUP
            refresh:true-data-id: @[email protected]
            group: DEFAULT_GROUP
            refresh:trueconfig:name: bootstrap

启动项目查看输出信息
在这里插入图片描述
发现读取的

config.name

为本地配置

bootstrap-dev.yml

中的信息。


本文转载自: https://blog.csdn.net/ctwy291314/article/details/129333307
版权归原作者 gmHappy 所有, 如有侵权,请联系我们删除。

“Spring Cloud集成Nacos实现本地配置优先 | Spring Cloud 9”的评论:

还没有评论