Spring Cloud Config简介
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库 中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。
Config Server
是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个 环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件 存储。
Config Client
是Config Server的客户端,用于操作存储在Config Server中的配置内容。 微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器。
详细内容看在线文档:https://springcloud.cc/spring-cloud-config.html
配置服务端
将配置文件提交到码云
使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接 的情况。如果我们希望体验Git飞一般的速度,可以使用国内的Git托管服务——码云 (gitee.com)。
和GitHub相比,码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。对于团队协作开发,码云还提供了项目管理、代码托管、文档管理的服务。
使用步骤:
- 浏览器打开gitee.com,注册用户 ,注册后登陆码云管理控制台
- 创建项目 javakf-config (点击右上角的加号 ,下拉菜单选择创建项目)
- 上传配置文件,将javakf_user工程的application.yml改名为user-dev.yml后上传
文件命名规则:
{application}-{profile}.yml
或{application}-{profile}.properties
application为应用名称 profile指的开发环境(用于区分开发环境,测试环境、生产环境 等)
配置中心微服务
(1)创建工程模块 配置中心微服务 javakf_config ,pom.xml引入依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
(2)创建启动类ConfigApplication
@SpringBootApplication @EnableEurekaClient @EnableConfigServer // 开启配置服务 public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } }
(3)编写配置文件application.yml
server: port: 20001 eureka: client: service-url: defaultZone: http://localhost:8888/eureka spring: application: name: javakf-config cloud: config: server: git: uri: https://gitee.com/qiuka/javakfconfig.git
(4)浏览器测试:http://localhost:20001/user-dev.yml 可以看到配置内容
配置客户端
(1)在javakf_user工程添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
(2)添加bootstrap.yml ,删除application.yml
eureka: client: service-url: defaultZone: http://localhost:8888/eureka spring: cloud: config: name: user profile: dev label: master discovery: enabled: true service-id: javakf-config
(3)测试: 启动工程javakf_eureka javakf_config javakf_user,看是否可以正常运行
http://localhost:10001/user/sms/1