(此次创建的Demo小案例都是基于springBoot【2.0.0.M3】,springCloud【Finchley.M2】创建的,读者若是为了演示正常,请务必保持版本一致)
下面讲解统一配置中心的简单使用
1.创建一个config Server的项目,我们就叫config
2.然后我们继续下一步,一定要按照下图红框圈中的两项选择
3.然后修改我们的版本
4.因为我们演示的版本比较旧,所以这里下载相关依赖jar 的时候下载不下来,所以需要手动配置一下下载镜像
在我们的pom文件中添加如下spring的镜像配置
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
5.启动类添加注解【@EnableDiscoveryClient】【@EnableConfigServer】
6.配置git仓库库的地址以及其他属性等
eureka:
client:
service.url:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: config
#我们git上仓库地址,这里我使用的是开源中国的git库
cloud:
config:
server:
git:
uri: https://gitee.com/xxx/SpringCloud.git
#用户名
username: xxx
#密码
password: xxx
#本地存放配置文件的地址,因为我们的配置中心会从从git上拉取配置文件然后存到本地一份,这个地址我们可以自定义配置
basedir: F:\config_basedir
7.本地config server 的项目基本配置完成。这时候我们在配置仓库地址的时候务必保证我们的git库上有我们需要的配置文件或者项目,至于如何在git上创建项目我就不多说了,这是我创建的一个仓库,里面包含了我们演示项目的配置文件【order.yml】
8.这时候我们启动我们本地的项目,访问地址http://localhost:8080/order-a.yml,便可以看到我们【order.yml】的文件内容,如下:
我们在访问的时候一定要注意访问文件的方式{name}-{profiles}.yml/json/properties
虽然我们的配置文件叫做【order.yml】,但是我们访问需要按照上面访问形式进行访问,可以是order-w.yml,也可以是order-g.yml,-后面可以是任意值,还有展示文件的形式我们可以是yml格式也是json等等
至于为什么要这种形式进行访问,比如我们的配置中心配置文件很多,关于order模块的就要分为测试,生产等不同的文件,这个时候我们可以将开发环境的配置写进【order-dev.yml】中,我们开发的时候就可以单独去加载开发环境的配置文件了,例如我本地git库上新创建了一个【order-dev.yml】的文件,具体访问如下图: