springcloud开发过程中为什么要用配置中心?有什么好处?
》
举个栗子:
使用微服务搭建项目过程中、每一个服务都要配置文件,当遇到大型项目时候,用户模块、订单模块、商品模块…数据使用单个数据源dataSource 的话,一旦数据库地址需要发生变化,无疑,仅仅配置文件url 只一块儿就很难想象;
众多依赖配置势必会出现重复配置(冗余),并且模块越多,项目的配置文件越不利于管理;为使配置系统有效的管理,我们引入Spring Cloud Config 组件;
Spring Cloud Config 组件是什么?
是一个高可用的分布式配置中心,它支持将配置存放到内存(本地),也支持将其放到 Git 仓库进行统一管理;
1、创建配置中心
1、创建Git仓库、我这里使用的GitHub
2、在项目中创建配置中心模块config
3、配置config/测试是否配置成功、成功继续往下、
4、修改各个服务配置。
1、我创建的GitHub仓库: https://github.com/medoo-Ai/springcloudConfig.git
2、创建模块config、该模块pom.xml添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
yml配置文件配置:
server:
port: 8888
spring:
application:
name: config
profiles:
active: dev
cloud:
config:
server:
git:
uri: https://github.com/medoo-Ai/springcloudConfig.git #配置git仓库地址、
searchPaths: springcloudConfig/config #配置仓库路径
username: 填写自己的用户名 #访问git仓库的用户名
password: 填写自己的密码 #访问git仓库的用户密码
label: master #配置仓库的分支
eureka:
instance:
hostname: ${spring.cloud.client.ipAddress}
instanceId: ${spring.cloud.client.ipAddress}:${server.port}
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
3、启动服务端Eureka 和配置中心 config
访问:http://localhost:8888/config/dev
4、显然成功了,有数据返回、接下来更改每一个模块的配置文件,以完成统一管理配置;
1、首先我们更改服务的提供者eurekaclient 、添加依赖;
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2、先更名application.yml为eurekaclient.yml 放在GitHub仓库的配置中心模块config下、删除resources目录更名后的配置文件、新建bootstrap.yml、
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8763
spring:
application:
name: eurekaclient
在eurekaclient 的resources目录下新建bootstrap.yml 以拉取远程的配置、
spring:
application:
name: eurekaclient
profiles:
active: dev
cloud:
config:
profile: dev #指定配置环境,配置文件如果是多环境则取名类似:config-dev.yml
name: eurekaclient #指定配置文件名字(多个配置文件以英文逗号隔开)
label: master #git仓库分支名
discovery:
enabled: true
serviceId: config #连接的配置中心名字(applicaiton.name)
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
分别启动 服务端EurekaServer、服务提供者eurekacllient、配置中心config
服务提供者的端口为8763、
修改GitHub上eurekaclient.yml 中的端口、重启服务提供者eurekacllient、发现其从Git上面拉取了配置、