天天看点

springcloud-config配置中心分布式管理

1、为什么要使用springcloud-config配置中心?

随着系统微服务的不断增加,首要考虑的是系统的可伸缩性、可扩展性,配置管理就是一个大问题。各自管各自的开发时没什么问题,到了线上之后管理就会很头疼,到了要大规模更新就更烦了。

肯定不能为了更新你的配置去停了你的服务集群,这是不现实的做法,因此springcloud配置中心就是一个比较好的解决方案:把微服务集群里面的配置抽象出来,交个文件仓库或者文件服务器去统一管理,每当想更新配置文件是只需要在文件仓库或者文件服务器上直接修改就成,不必再去挨个应用去修改配置文件。

2、spring cloud config包括两部分组成

1.spring cloud config server 作为配置中心的服务端:

  1.拉取配置时更新git仓库副本,保证是最新结果

  2.支持数据结构丰富,yml, json, properties 等

  3.配合 eureke 可实现服务发现,配合 cloud bus 可实现配置推送更新

  4.配置存储基于 git 仓库,可进行版本管理

  5.简单可靠,有丰富的配套方案

2.Spring Cloud Config Client 客户端:

  1.Spring Boot项目不需要改动任何代码,加入一个启动配置文件指明使用ConfigServer上哪个配置文件即可

3、spring cloud config的简单搭建

1.搭建spring cloud config server 服务端:

步骤一:新建一个springcloud-config-server工程,并引入以下依赖:

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-config-server</artifactId>
</dependency>
           

步骤二:在启动类上加入@EnableConfigServer注解,表示这个是配置中心服务端:

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class SpringConfigServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringConfigServerApplication .class, args);
	}

}
           

步骤三:添加配置文件及配置项、application.yml配置如下:

spring:
  cloud:
    config:
      server:
        git:
#GitHub上的链接
          uri: https://github.com/****/config-git.git
#用户名
          username: ***
#密码
          password: *****
#服务端的服务名
  application:
    name: spring-config-server
server:
    port: 9090
eureka:
#  instanc中的配置是让该服务使用IP注册到注册中心,而不是hostname
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: false
    fetch-registry: false
           

步骤四:在GitHub新建一个仓库,在新建应用所需的配置文件:

springcloud-config配置中心分布式管理

步骤五:启动config服务端并访问:

springcloud-config配置中心分布式管理

2、搭建spring cloud config 客户端:

步骤一:在现有的微服务应用上添加以下依赖:

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

步骤二:在client端中添加bootstrap.yml文件,并添加配置

springcloud-config配置中心分布式管理
spring:
  cloud:
    config:
#服务端的服务名
      name: spring-config-server
#环境的配置文件,生产环境、开发环境等
      profile: dev
#服务端的链接
      uri: http://localhost:9090/
#分支,master、develop等
      label: master
           

为什么要加一个bootstrap.yml文件呢?因为springboot工程默认的加载配置文件顺序bootstrap.yml在application之前。

步骤三:写一段测试代码:

springcloud-config配置中心分布式管理

步骤四:启动并访问:

springcloud-config配置中心分布式管理

 以上为springcloud config的server端client端的简单实现,以上模式还有一个缺陷:当文件仓库里面的配置修改时,微服务client端的参数不会立即修改,得重启client端后才能加载修改后的配置。下一章将简单记录springcloud-bus怎样解决这一问题。

继续阅读