Skip to content

Latest commit

 

History

History
177 lines (129 loc) · 3.5 KB

配置中心.md

File metadata and controls

177 lines (129 loc) · 3.5 KB

配置中心

在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库 中。在spring cloud config 组件中,分两个角色,一是config server,二是config client

20203620834

配置中心应该提供的功能

  • 服务端与客户端支持
  • 集中管理各环境的配置文件
  • 修改之后可以快速生效
  • 版本管理
  • 并发查询
  • 多语言支持

服务端

  • 依赖
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  • 配置
server:
  port: 8003
spring:
  application:
    name: spring-cloud-config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/0xcaffebabe/config/     # 配置git仓库的地址
          search-paths: config1                               # git仓库地址下的相对地址,可以配置多个,用,分割。
@EnableConfigServer
  • 仓库中的文件

    批注 2019-07-24 161419

这时候访问 server/config/dev即可获取配置信息

客户端

  • 依赖
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  • 配置

    • application.properties

      server.port=8004
      spring.application.name=config-client
    • bootstrap.properties

      spring.cloud.config.name=config
      spring.cloud.config.profile=dev
      spring.cloud.config.uri=http://localhost:8003/
      spring.cloud.config.label=master
  • 获取

@Value("${config.hello}")
  private String port;

配置刷新

  • 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 开启更新机制
@RestController
// 一定要加这个
@RefreshScope
public class MyController {

    @Value("${config.hello}")
    private String port;

    @RequestMapping("/hello")
    public String hello(){
        return port;
    }
}
  • 配置
management.endpoints.web.exposure.include=refresh,health,info

当配置文件发生更新时,调用客户端接口刷新配置

curl -X POST http://localhost:8004/actuator/refresh

发起对该地址的请求可让客户端去向配置中心获取最新配置并应用到相关成员变量上

配置中心服务化

  • 添加依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8001/eureka/   # 注册中心eureka地址
@EnableDiscoveryClient

客户端改造

  • 添加依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • 删除 spring.cloud.config.uri

  • 添加

    • spring.cloud.config.discovery.enabled
    • spring.cloud.config.discovery.serviceId
    • eureka.client.serviceUrl.defaultZone
    • @EnableDiscoveryClient

高可用

启动多个配置中心实例