04-配置中心详解

张开发
2026/4/11 12:16:42 15 分钟阅读

分享文章

04-配置中心详解
Spring Cloud 配置中心详解一、知识概述配置中心是微服务架构中管理分布式系统配置的核心组件,它实现了配置的集中管理、动态更新和环境隔离。Spring Cloud 提供了 Spring Cloud Config 和支持 Nacos 等配置中心的集成方案。配置中心的核心功能:集中管理:统一管理所有服务的配置动态更新:无需重启即可更新配置环境隔离:开发、测试、生产环境配置隔离版本管理:配置变更历史追溯理解配置中心的原理和使用方式,是构建可维护微服务系统的重要技能。二、知识点详细讲解2.1 配置中心对比特性Spring Cloud ConfigNacosApollo配置存储Git/SVN数据库数据库动态刷新需要总线原生支持原生支持灰度发布❌✅✅权限管理Git 权限✅✅多环境ProfileNamespaceEnv学习成本低低中2.2 Spring Cloud Config 架构配置客户端 Config Server Git/SVN │ │ │ │──── 获取配置 ──────────│ │ │ │──── 拉取配置 ──────────│ │ │ │ │─── 返回配置 ───────────│─── 返回配置 ───────────│ │ │ │ │──── 刷新通知 ──────────│ │ │ │ │2.3 配置优先级1. 命令行参数 2. Java 系统属性 3. 环境变量 4. 外部配置文件 5. 内部配置文件 6. @PropertySource 7. 默认属性2.4 配置文件加载顺序1. bootstrap.yml(启动配置) 2. application.yml(应用配置) 3. application-{profile}.yml(环境配置) 4. 配置中心配置 5. 命令行参数三、代码示例3.1 Spring Cloud Config Server!-- pom.xml --dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-config-server/artifactId/dependencyimportorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.config.server.EnableConfigServer;@SpringBootApplication@EnableConfigServerpublicclassConfigServerApplication{publicstaticvoidmain(String[]args){SpringApplication.run(ConfigServerApplication.class,args);}}# application.ymlserver:port:8888spring:application:name:config-servercloud:config:server:git:uri:https://github.com/example/config-reposearch-paths:'{application}'default-label:mainusername:${GIT_USERNAME}password:${GIT_PASSWORD}clone-on-start:truebasedir:/tmp/config-repo# 本地文件系统配置(开发环境)# config:# server:# native:# search-locations: classpath:/config# profiles:# active: native3.2 Spring Cloud Config ClientdependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-config/artifactId/dependency# bootstrap.ymlspring:application:name:user-serviceprofiles:active:devcloud:config:uri:http://localhost:8888label:mainfail-fast:trueretry:initial-interval:1000max-interval:2000max-attempts:6multiplier:1.1importorg.springframework.beans.factory.annotation.Value;importorg.springframework.cloud.context.config.annotation.RefreshScope;importorg.springframework.web.bind.annotation.*;@RestController@RefreshScope// 支持动态刷新publicclassConfigController{@Value("${app.message:default}")privateStringmessage;@Value("${app.timeout:3000}")privateinttimeout;

更多文章