SpringCloud微服务(学习笔记):配置中心 Config

测试用项目环境

框架版本
Idea2019.2
JDK1.8
SpringBoot2.1.6.RELEASE
SpringCloudGreenwich.SR2

配置中心

顾名思义,可以将微服务系统中公用的配置提取出来统一管理,一次修改,面面俱到

相关产品

当前生态下配置中心有很多产品,公司内还会有自己开发的配置中心

Config Server 配置中心搭建

创建一个新的SpringBoot引用

maven依赖

使用maven依赖管理,使用最新的springcloud Greenwich.SR2版本

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Greenwich.SR2</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
</dependencyManagement>

配置中心同样需要注册到注册中心去所以需要eureka依赖

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

config-server配置中心关依赖

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<!--此处并不是starter-->
	<artifactId>spring-cloud-config-server</artifactId>
</dependency>

启动类注解

@EnableConfigServer

git管控中心

个人感觉Config Server相当于一个中转站,所以实际配置文件存放的地方是各种关系非关系形数据库,或git服务器。我此处采用了github私有仓库作为配置文件的存放地。
github上建好仓库生成一个url

application.yml配置
spring:
  cloud:
    config:
      server:
        git:
          username: your github username
          password: your github password
          uri: your repository uri exp https://github.com/lmwis/course-except.git
          # 超时时间
          timeout: 4
          # 默认分支
          default-label: master

配置好之后启动

演示github内容:
在这里插入图片描述
浏览器访问:
http://localhost:9090/master/test-master.yml
你就会得到:
在这里插入图片描述
后缀修改为json,config server还会帮你吧yml转化为json

命名规则

/{name}-{profiles}.properties
/{name}-{profiles}.yml
/{name}-{profiles}.json
/{label}/{name}-{profiles}.yml

name 文件名称
profile 环境名称,开发、测试、生产
lable 仓库分支、默认master分支

客户端使用配置中心

maven依赖

<!--配置中心-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-config-client</artifactId>
</dependency>

yml配置

第一步

先将配置文件名application.yml替换为bootstrap.yml
在这里插入图片描述
从此application改名为bootstrap
我也很难接受

spring:
	application:
	    name: test-service
	cloud:
	    config:
	      discovery:
	      	# 启用,必须为true
	        enabled: true
	        # 配置中心在注册中心的服务名 会自动负载均衡
	        service-id: FEHEAD-CONFIG-SERVER
	      # 指定当前分支
	      # 现在访问到的 /master/test-service-master.yml
	      # git上的文件名是test-service
	      profile: master

然后就可以像正常情况一样使用配置文件了

特别注意

如果你的git上有一个名为application.yml的配置文件
那么你当前git分支下的所有配置文件都会默认把application.yml加在一起,但application.yml的优先级比较低,同名字会被项目的配置文件覆盖

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值