Spring cloud config 使用实例

总结:

Spring Cloud Config 是一种用来动态获取Git、SVN、本地的配置文件的一种工具

如果微服务架构中没有使用统一配置中心时,所存在的问题:

    配置文件分散在各个项目里,不方便维护 配置内容安全与权限,实际开发中,开发人员是不知道线上环境的配置的 更新配置后,项目需要重启

目录结构

服务端pom文件

<dependencies> <!--配置中心--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <!--web 模块--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--undertow容器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> </dependencies>

服务端启动类

@EnableConfigServer //注解来开启config 的server功能 @SpringCloudApplication public class WildCatConfigApplication { public static void main(String[] args) { SpringApplication.run(WildCatConfigApplication.class, args); } }

服务端yml文件

server: port: 2001 spring: application: name: @artifactId@ profiles: active: native # 配置中心 cloud: config: server: native: // 本地文件,可配置svn git 自行百度配置 search-locations: classpath:/config/ # 注册中心配置 eureka: instance: prefer-ip-address: true client: service-url: defaultZone: http://wildcat:wildcat@wildcat-eureka:1021/eureka/

客户端pom文件

<dependencies> <!--Spring Cloud Config 客户端依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!-- web的依赖,必须加 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Spring Boot Actuator,感应服务端变化--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>

客户端yml文件

spring: application: name: @artifactId@ # 配置中心 cloud: config: fail-fast: true name: ${spring.application.name} // 应用名 profile: ${spring.profiles.active} // 环境名 ps:可配置到pom文件中去 discovery: enabled: true service-id: pigx-config autoconfigure: exclude: org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration main: allow-bean-definition-overriding: true profiles: active: dev
    spring.application.name:对应文件规则的应用名 spring.cloud.config.profile:对应环境名 spring.cloud.config.label:对应分支名 spring.cloud.config.uri:对应Config Server开放的地址

Config支持我们使用的请求的参数规则为:

    / { 应用名 } / { 环境名 } [ / { 分支名 } ] / { 应用名 } - { 环境名 }.yml / { 应用名 } - { 环境名 }.properties / { 分支名 } / { 应用名 } - { 环境名 }.yml / { 分支名 } / { 应用名 } - { 环境名 }.properties
经验分享 程序员 微信小程序 职场和发展