Spring Cloud 六:分布式配置中心【Dalston版】

Spring Cloud Config 它分为服务端与客户端两个部分。

其中服务端也称为分布式配置中心,它是一个独立的微服务应用,用来连接配置仓库并为客户端提供获取配置信息;

而客户端则是通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息

简而言之 服务端设置我们的配置,客户端从服务端获取配置

准备配置仓库

  • 准备一个git仓库,可以在码云或Github上创建都可以。比如本文准备的仓库示例:http://git.oschina.net/didispace/config-repo-demo

  • 假设我们读取配置中心的应用名为config-client,那么我们可以在git仓库中该项目的默认配置文件config-client.yml

  • 构建配置中心

    通过Spring Cloud Config来构建一个分布式配置中心非常简单,只需要三步:

    • 创建一个基础的Spring Boot工程,命名为:config-server-git,并在pom.xml中引入下面的依赖(省略了parent和dependencyManagement部分):
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

创建Spring Boot的程序主类,并添加@EnableConfigServer注解,开启Spring Cloud Config的服务端功能

@EnableConfigServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

在 application.yml中添加配置服务的基本信息以及Git仓库的相关信息,例如:

spring
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: http://git.oschina.net/didispace/config-repo-demo/
server:
  port: 1201

并使用Git管理配置内容的分布式配置中心就已经完成了

访问:

url 映射关系

  • /{application}/{profile}[/{label}]
  • 其中{label}对应Git上不同的分支,默认为master

构建客户端

在完成了上述验证之后,确定配置服务中心已经正常运作,下面我们尝试如何在微服务应用中获取上述的配置信息

  • 创建一个Spring Boot应用,命名为config-client,并在pom.xml中引入下述依赖:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
</dependencies>
  • 创建Spring Boot的应用主类,具体如下:
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

创建bootstrap.yml配置,来指定获取配置文件的config-server-git位置,例如

spring:
  application:
    name: config-client
  cloud:
    config:
      uri: http://localhost:1201/
      profile: default
      label: master

server:
  port: 2001
原文地址:https://www.cnblogs.com/lyon91/p/8794136.html