SpringCloud Config

为什么需要配置中心

单体应用,配置写在配置文件中,没有什么大问题。如果要切换环境 可以切换不同的profile(2种方式),但在微服务中。

  1. 微服务比较多。成百上千,配置很多,需要集中管理。

  2. 管理不同环境的配置。

  3. 需要动态调整配置参数,更改配置不停服。

配置中心介绍

分布式配置中心包括3个部分:

  1. 存放配置的地方:git ,本地文件 等。
  2. config server。从 1 读取配置。
  3. config client。是 config server 的客户端 消费配置。

例子

新建ConfigServer模块,加入依赖:

     <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>

 

在application.properties配置:

server.port=7010

spring.application.name=configServer

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

spring.cloud.config.server.git.uri=https://gitee.com/xxxx/config-center.git
spring.cloud.config.server.git.username=你的用户名
spring.cloud.config.server.git.password=你的密码
spring.cloud.config.label=master

spring.cloud.config.server.bootstrap=true

这里用gitee演示。在上面配置的git仓库中加入配置文件consumer-dev.properties:

test1=123

 
配置文件名规则为:

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

文件后缀可以是properties,yml等。label是仓库分支、默认master分支,name是服务名称,profile是环境名称,比如开发,测试,生产。consumer-dev.properties配置文件是consumer服务在开发环境所使用的。
 
启动类加@EnableConfigServer注解,启动后访问http://localhost:7010/master/consumer-dev.properties,看到浏览器展示test1: 123

 
 

在ConsumerByRibbon加入配置中心客户端依赖:

		<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-config-client</artifactId>
	</dependency>

 

在bootstrap.properties配置:

#直接URL方式查找配置中心
spring.cloud.config.uri=http://localhost:7010/
#通过注册中心查找
#spring.cloud.config.discovery.enabled=true
#spring.cloud.config.discovery.service-id=configServer
spring.cloud.config.profile=dev
spring.cloud.config.label=master

 

在controller中加入:

 @Value("${test1}")
  private String test1;

 @GetMapping("/getConfig")
  public String getConfig() {
      return test1;
  }

启动后访问http://localhost:8003/getConfig,看到展示123。将bootstrap.properties修改为:

#直接URL方式查找配置中心
#spring.cloud.config.uri=http://localhost:7010/
#通过注册中心查找
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=configServer
spring.cloud.config.profile=dev
spring.cloud.config.label=master

重启后访问http://localhost:8003/getConfig,可看到和上面相同的结果。

 
 

将git仓库上的 consumer-dev.properties文件内容改为:

test1=1234

访问http://localhost:8003/getConfig,看到123,不是git仓库最新配置。

手动配置热更新

  1. 开启actuator中的refresh端点
  2. Controller中添加@RefreshScope注解
  3. 向客户端 url http://localhost:8003/actuator/refresh发送Post请求

 
Controller中添加@RefreshScope注解重启ConsumerByRibbon访问http://localhost:8003/getConfig看到最新配置。将git仓库上的 consumer-dev.properties文件内容改为:

test1=12345

 

通过postman向客户端 url http://localhost:8003/actuator/refresh发送Post请求后访问http://localhost:8003/getConfig,看到最新配置12345。

posted @ 2023-04-05 17:01  shigp1  阅读(41)  评论(0)    收藏  举报