摘要: 原创出处 http://www.iocoder.cn/Spring-Boot/config-nacos/ 「芋道源码」欢迎转载,保留摘要,谢谢!

  • 1. 概述
  • 2. 快速入门
  • 3. 多环境配置
  • 4. 自动刷新配置
  • 5. 配置加密
  • 6. 监控端点
  • 7. 配置加载顺序
  • 666. 彩蛋

本文在提供完整代码示例,可见 https://github.com/YunaiV/SpringBoot-Labs 的 lab-44 目录。

原创不易,给点个 Star 嘿,一起冲鸭!

1. 概述

在《Nacos 极简入门》中,我们已经学习了如何搭建一个 Nacos 服务。如果还没有的胖友,赶紧先去简单学习下,重点是跟着该文「2. 单机部署」小节,自己搭建一个 Nacos 服务。

本文,我们来学习下如何在 Spring Boot 中,将 Nacos 作为一个配置中心,实现分布式环境下的配置管理。

友情提示:对 Nacos 作为注册中心感兴趣的胖友,可以看看《芋道 Spring Boot 注册中心 Nacos 入门》文章。

2. 快速入门

示例代码对应仓库:lab-44-nacos-config-demo。

本小节,我们会在 Nacos 服务中定义配置,并使用 @ConfigurationProperties 和 @Value 注解,读取该配置。

友情提示:如果胖友看过《芋道 Spring Boot 配置文件入门》的「2. 自定义配置」小节,就会发现本小节是对标这块的内容。

如果没看过,也没关系,艿艿只是提一下而已,嘿嘿。继续往下看即可。

2.1 引入依赖

在 pom.xml 文件中,引入相关依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>lab-44-nacos-config-demo</artifactId>

    <dependencies>
        <!-- Spring Boot Starter 基础依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 实现对 Nacos 作为配置中心的自动化配置 -->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.4</version>
        </dependency>
    </dependencies>

</project>
  • 重点是引入 nacos-config-spring-boot-starter 依赖,实现对 Nacos 作为配置中心的自动化配置。

2.2 配置文件

在 application.yml 中,添加 Nacos 配置,如下:

nacos:
  # Nacos 配置中心的配置项,对应 NacosConfigProperties 配置类
  config:
    server-addr: 127.0.0.1:18848 # Nacos 服务器地址
    bootstrap:
      enable: true # 是否开启 Nacos 配置预加载功能。默认为 false。
      log-enable: true # 是否开启 Nacos 支持日志级别的加载时机。默认为 false。
    data-id: example # 使用的 Nacos 配置集的 dataId。
    type: YAML # 使用的 Nacos 配置集的配置格式。默认为 PROPERTIES。
    group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP。
    namespace: # 使用的 Nacos 的命名空间,默认为 null。

nacos.config 配置项,为 Nacos 作为配置中心的配置,对应 NacosConfigProperties 配置类。