当你使用Eureka作为注册中心时候,Eureka他是没有配置中心的,因此我们需要另一个组件对项目进行配置的管理 Spring Cloud Config (下面可能用SCC简称)
两种存配置的方法
1.数据库或者是磁盘
2.git仓库(git会记录历史版本,SCC默认存在GIT仓库)
使用步骤
1.准备Git仓库:查看idea是否配置GIT
2.在父项目的目录下新建文件夹config
3.复制要交给SCC要进行管理服务的配置到Config里
profile的用法:
主配置与很多profile配置,用哪个配置需要自己指定
user-service-dev
user-service-text
user-service-pro
4.创建本地仓库(如果已经创建过仓库,不要重复创建)
- 双击两下SHIFT 找到create git repositoy 指定对应的文件夹
- 双击两下SHIFT 找到commit,全部提交
6.在gitee 新建仓库springcloud1(设置为开源)
7.双击shift 然后点击Define Remote 点击Ok push 将对应的git仓库地址写到url框里
8.注意:配置中心的配置优先使用,本地启动参数没用了就,为防止下载的配置覆盖本地启动参数
在上交到配置中心的配置文件中添加一个属性:之后commit到本地 → push到远程仓库
9.如果配置中心有问题,可能是仓库的问题,果断换一个仓库!测试
搭建配置中心
1.新建spring模块 sp09-config
2.添加依赖:
eureka 客户端
conifg sever
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3.yml
git仓库地址
存放配置文件的文件夹(若文件夹有层级要把层级写清楚)
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://gitee.com/mambaout824/spring-cloud-v
search-paths: config #一层就这么写
#两层 springcloud1/config
server:
port: 6001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka
4.添加启动类注解
@EnableConfigServer 在config server 依赖里的
配置中心客户端
1.若原来服务中有application.yml,将其中的内容全部删除或者注释
2.pom.xml加入spring.cloud.starter.config依赖与eureka的客户端依赖
3.新建bootstarp.yml(引导配置)
- 访问注册表
- 指定配置中心的service id
- 指定下载的配置文件
eureka: #配置eureka 注册到注册表
client:
service-url:
#默认地点
#可以重云服务器购买不同地点的服务器
defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka
spring:
cloud:
config:
discovery:
enabled: true #允许服务被发现
service-id: config-server #注册表里注册的config名字
name: user-service #查找的配置文件名
profile: dev #查找的profile后缀
4.启动服务测试
启动日志开头出现从服务器获取配置localhost:6001,并且可以拉取就对了
2022-02-21 15:57:08.969 INFO 2160 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://8LaVine:6001/
2022-02-21 15:57:11.321 INFO 2160 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=user-service, profiles=[dev], label=null, version=e2a043c809d87ffccd3ede3fefd12f11a36396d0, state=null
2022-02-21 15:57:11.322 INFO 2160 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}, BootstrapPropertySource {name='bootstrapProperties-https://gitee.com/mambaout824/spring-cloud-v/config/user-service-dev.yml'}]
项目启动顺序
1.eureka 等待完全启动完成
2.SCC 等待完全启动完成
3. 去eureka看一下注册表,看SCC是否成功注册(若SCC没开,服务的配置文件交给他了,还启动,就会使用默认的8888端口)
4.之后再去启动其他模块 例 02(商品服务) 03(用户服务) 04(订单服务) 06(zuul网关服务)