1.什么是springcloud-config?
Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring
Environment
和PropertySource
抽象相同,因此它们与Spring应用程序非常契合,但可以与任何以任何语言运行的应用程序一起使用。随着应用程序通过从开发人员到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具。可以轻松添加替代实现,并使用Spring配置将其插入。(官网文档)
2.springcloud-config具体作用
springcloud-config是一个分布式的配置文件管理中心,可以获取存储在本地或者远程的配置文件。运用在在分布式系统中,方便服务配置文件统一管理,实时更新。spring cloud config 组分为config server和config client,当服务启动时,会请求config server获取相应的配置文件内容,然后加载到容器中并启动,获取配置的微服务都相当于一个config client。
3.具体步骤
-
1.在gitte上创建一个仓库并上传相应的配置文件,记录好HTTPS地址,这就是远程调用的配置文件
-
2.创建一个用作配置服务器的springboot项目,它的作用是从gitte上远程读取仓库中的文件并把它们保存到本地,以供调用。默认文件保存地址:C:/Users/当前用户/AppData/Local/Temp/config-repo-xxxxxx/。
(1):项目依赖
<!--config server --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
(2):application.yaml
server: port: 3344 spring: application: name: 项目名字 cloud: config: server: git: uri: 上面记录的HTTPS地址(仓库的地址)
(3):在项目的主启动类加上注解
@EnableConfigServer //开启服务配置注解
-
3.创建一个注册中心,管理各类服务
(1):依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <!-- config client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
(2):bootstrap.yaml: (系统级配置,与application.yaml作用差不多,但优先级更高)
spring: cloud: config: name: config-eureka # 需要从git上读取的资源名称,不需要加后缀 profile: dev label: master uri: http://localhost:3344 #本地配置服务器项目地址,获取配置信息
(3):在项目的主启动类加上注解
@EnableEurekaServer //服务端启动类注解,可以接受别人注册进来
-
4.创建一个服务项目,将自己注册进注册中心,并从配置服务期项目上获取配置信息
(1):必备依赖
<!-- config client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
(2):bootstrap.yaml: (系统级配置,其他配置远程获取)
spring: cloud: config: name: config-dept # 需要从git上读取的资源名称,不需要加后缀 profile: dev label: master uri: http://localhost:3344 #本地配置服务器项目地址,获取配置信息
(3):其他业务代码
-
效果展示
远程获取配置连接成功: