SpringCloud系列(五)分布式配置中心

这是我参与更文挑战的第 15 天,活动详情查看: 更文挑战

Spring Cloud Config

一、概述

随着服务的模块增多,对应的配置文件也会越来越多,并且存在多个环境不同的配置,配置文件的维护和管理就变得困难。所以需要一套集中式的、动态的配置管理设施、
Spring Cloud Config为微服务架构中的微服务提供了集中化的外部配置支持,配置服务为各个不同的微服务应用的所有环境提供了一个中心化的外部配置、
Config作用

  • 集中管理配置文件
  • 根据不同的环境提供不同的配置文件
  • 运行期动态调整配置,服务会响配置中心拉取配置自己的信息。
  • 配置发生变动服务不需要重启即可感知到。
  • 配置信息以REST接口的形式风格暴露

二、配置中心搭建

使用Github整合配置,把配置信息放到Github上。

依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
复制代码

配置

server:
  port: 3344
spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://github.com/812467457/springcloud-config.git
          # 搜索目录
          search-paths: springcloud-config
      # 读取的分支
      label: main
复制代码

主启动

@SpringBootApplication
@EnableConfigServer //激活配置中心
public class ConfigMain3344 {
    public static void main(String[] args) {
        SpringApplication.run(ConfigMain3344.class, args);
    }
}
复制代码

测试:访问http://localhost:3344/main/config-dev.yml,即可访问到的该配置。如果其他环境的配置访问到config-prod.yml即可。如果访问其他分支,把main改为其他分支即可。

三、Config客户端搭建

读取配置中心、
使用一个bootstrap.yml,比application.yml优先级更高,从bootstrap.yml找到配置中心的具体配置,然后拼接为最后的配置。

配置

server:
  port: 3355
spring:
  application:
    name: config-client
  cloud:
    config:
      label: main   #分支名称
      name: config  # 配置名称
      profile: dev  # 后缀名   拼起来后就是http://localhost:3344/main/config-dev.yml
      uri: http://localhost:3344  # 配置中心地址
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #defaultZone: http://eureka7001.com:7001/eureka
      defaultZone: http://santi-PC:7001/eureka
复制代码

业务类

@RestController
public class ConfigClientController {
    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/get/info")
    public String getInfo(){
        return configInfo;
    }
}
复制代码

测试:访问http://localhost:3355/get/info通过github获取配置中心的配置

四、动态刷新

修改GitHub中的配置,配置中心3344会随之动态变化,而配置中心客户端3355不会变化,需要重启才能生效。
客户端3355添加动态刷新功能。

依赖必须添加actuator

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
复制代码

添加配置暴露监控断点

management:
  endpoints:
    web:
      exposure:
        include: "*"
复制代码

业务类加刷新注解@RefreshScope

@RefreshScope
@RestController
public class ConfigClientController {}
复制代码

注意:需要配合一个post请求http://localhost:3355/actuator/refresh,以上配置才会生效

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享