spring cloud config 详解

spring cloud config 详解

Spring Cloud 为开发人员提供了一系列的工具来快速构建分布式系统的通用模型 。例如:配置管理、服务发现、断路由、智能路由、微代理、控制总线、一次性Token、全局锁、决策竞选、分布式session、集群状态等等。分布式系统的协助需要一大堆的模型,使用Spring Cloud开发者能快速的建立支持实现这些模式的服务和应用程序。他们将适用于任何分布式环境,无论是开发者的个人电脑还是生产环境,还是云平台。

版本:Brixton.SR3 
作者:链上研发-欧阳 
(注:阅读前置技能树 Spring 以及Spring的 Property Source、Environment、Profile 和 Spring Boot ,原始文档有些没头没尾的,适当添加了些内容。)

Spring Cloud中文文档(持续更新中。。。)

特性

Spring Cloud 专注于提供良好开箱即用的典型方案和可扩展方式。

  • 分布式/版本化配置
  • 服务注册/服务发现
  • 路由
  • 服务间调用
  • 负载均衡
  • 断路器
  • 全局锁
  • 领导选取和集群状态监控
  • 分布式消息

Cloud Native 应用

Cloud Native是一种持续交付和价值驱动开发推荐的最佳实践方式。它的理念包含了DevOps、持续交付、微服务、敏捷基础设施、康威定律,以及根据商业能力对公司进行重组。一个很好的契约例子是12-factor AppsSpirng Cloud 提供了一系列的工具和特性来促进这些开发,所有的组件都是基于分布式,并且非常容易开始使用。

构建Spring Cloud的大部分特性都是基于Spring Boot的。Spring Cloud的一些特性来源于两个库:Spring Cloud Context 和 Spring Cloud Commons。Spring Cloud Context为Spring Cloud应用程序的ApplicationContext提供了基础的服务(启动上下文,加密,刷新作用域和环境端点)Spring Cloud Commons是为实现不同的Spring Cloud实现的抽象。(例如:Spring Cloud Netflix 和 Spring Cloud Consul)

如果使用Sun的JDK遇到Illegal key size异常,需要安装JCE 
更多信息请查看:

提取文件到JDK/jre/lib/security文件夹(无论你使用的那个版本的JRE/JDK x64/x86)

  • 注意: 
    Spring Cloud是基于非限制性的Apache 2.0 license发布的。如果你发现文档有问题,或只是想提高它们的质量,请到 github上参与进来

Spring Cloud 上下文

Spring Boot使用约定的方式来构建Spring应用,例如:它约定了配置文件的位置、通用的端点管理和监控任务。Spring Cloud建立在它的上面,并且增加了一些分布式系统可能需要的组件。

启动上下文

Spring Cloud会创建一个`Bootstrap Context`,作为Spring应用的`Application Context`的父上下文初始化的时候,`Bootstrap Context`负责从外部源加载配置属性并解析配置这两个上下文共享一个从外部获取的`Environment`。`Bootstrap`属性有高优先级,默认情况下,它们不会被本地配置覆盖。`Bootstrap context`和`Application Context`有着不同的约定,所以新增了一个`bootstrap.yml`文件,而不是使用`application.yml` (或者`application.properties`)。保证`Bootstrap Context`和`Application Context`配置的分离。下面是一个例子: **bootstrap.yml**

复制代码
spring:
  application:
    name: foo
  cloud:
    config:
      uri: ${SPRING_CONFIG_URI:http://localhost:8888}
复制代码

 

推荐在`bootstrap.yml` or `application.yml`里面配置`spring.application.name`. 你可以通过设置`spring.cloud.bootstrap.enabled=false`来禁用`bootstrap`。

应用上下文层次结构

如果你通过`SpringApplication`或者`SpringApplicationBuilder`创建一个`Application Context`,那么会为spring应用的`Application Context`创建父上下文`Bootstrap Context`。在Spring里有个特性,子上下文会继承父类的`property sources` and `profiles` ,所以`main application context` 相对于没有使用Spring Cloud Config,会新增额外的`property sources`。额外的`property sources`有:

  • “bootstrap” : 如果在Bootstrap Context扫描到PropertySourceLocator并且有属性,则会添加到CompositePropertySourceSpirng Cloud Config就是通过这种方式来添加的属性的,详细看源码ConfigServicePropertySourceLocator`。下面也也有一个例子自定义的例子。
  • “applicationConfig: [classpath:bootstrap.yml]” ,(如果有spring.profiles.active=production则例如 applicationConfig: [classpath:/bootstrap.yml]#production): 如果你使用bootstrap.yml来配置Bootstrap Context,他比application.yml优先级要低。它将添加到子上下文,作为Spring Boot应用程序的一部分。下文有介绍。

由于优先级规则,Bootstrap Context不包含从bootstrap.yml来的数据,但是可以用它作为默认设置。(其实就是最低的优先级,测试过)

你可以很容易的扩展任何你建立的上下文层次,可以使用它提供的接口,或者使用SpringApplicationBuilder包含的方法(parent()child()sibling()Bootstrap Context将是最高级别的父类。扩展的每一个Context都有有自己的bootstrap property source(有可能是空的)。扩展的每一个Context都有不同spring.application.name。同一层层次的父子上下文原则上也有一有不同的名称,因此,也会有不同的Config Server配置。子上下文的属性在相同名字的情况下将覆盖父上下文的属性。

注意SpringApplicationBuilder允许共享Environment到所有层次,但是不是默认的。因此,同级的兄弟上下文不在和父类共享一些东西的时候不一定有相同的profiles或者property sources

修改Bootstrap属性配置

源码位置BootstrapApplicationListener

复制代码
   String configName = environment.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");

    String configLocation = environment.resolvePlaceholders("${spring.cloud.bootstrap.location:}");

    Map<String, Object> bootstrapMap = new HashMap<>();bootstrapMap.put("spring.config.name",configName);
    if(StringUtils.hasText(configLocation)){
        bootstrapMap.put("spring.config.location", configLocation);
    }
复制代码

 

 

bootstrap.yml是由spring.cloud.bootstrap.name(默认:”bootstrap”)或者spring.cloud.bootstrap.location(默认空)。这些属性行为与spring.config.*类似,通过它的Environment来配置引导ApplicationContext。如果有一个激活的profile(来源于spring.profiles.active或者Environment的Api构建),例如bootstrap-development.properties 就是配置了profiledevelopment的配置文件.

覆盖远程属性

property sourcesbootstrap context 添加到应用通常通过远程的方式,比如”Config Server”。默认情况下,本地的配置文件不能覆盖远程配置,但是可以通过启动命令行参数来覆盖远程配置如果需要本地文件覆盖远程文件,需要在远程配置文件里设置授权 
spring.cloud.config.allowOverride=true(这个配置不能在本地被设置)。一旦设置了这个权限,你可以配置更加细粒度的配置来配置覆盖的方式,

比如: 
spring.cloud.config.overrideNone=true 覆盖任何本地属性 
spring.cloud.config.overrideSystemProperties=false 仅仅系统属性和环境变量 
源文件见PropertySourceBootstrapProperties

自定义启动配置

bootstrap context是依赖/META-INF/spring.factories文件里面的org.springframework.cloud.bootstrap.BootstrapConfiguration条目下面,通过逗号分隔的Spring  @Configuration类来建立的配置。任何main application context需要的自动注入的Bean可以在这里通过这种方式来获取这也是ApplicationContextInitializer建立@Bean的方式。可以通过@Order来更改初始化序列,默认是”last”。

# spring-cloud-context-1.1.1.RELEASE.jar
# spring.factories
# AutoConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration # Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.cloud.bootstrap.BootstrapApplicationListener,\ org.springframework.cloud.context.restart.RestartListener # Bootstrap components org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration,\ org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration,\ org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\ org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
  • 警告 

    小心,你添加的自定义BootstrapConfiguration类没有错误的@ComponentScanned到你的主应用上下文,他们可能是不需要的。使用一个另外的包不被@ComponentScan或者@SpringBootApplication注解覆盖到。


bootstrap context通过spring.factories配置的类初始化的所有的Bean都会在SpingApplicatin启动前加入到它的上下文里去。

自定义引导配置来源:Bootstrap Property Sources

默认的`property source`添加额外的配置是通过配置服务(Config Server),你也可以自定义添加`property source`通过实现`PropertySourceLocator`接口来添加你可以使用它加配置属性从不同的服务、数据库、或者其他。

  • 下面是一个自定义的例子:
复制代码
@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {

    @Override
    public PropertySource<?> locate(Environment environment) {
        return new MapPropertySource("customProperty",
                Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
    }
}
复制代码

 

EnvironmentApplicationContext建立,并传入property sources(可能不同个profile有不同的属性),所以,你可以从Environment寻找找一些特别的属性。比如spring.application.name,它是默认的Config Server property source

如果你建立了一个jar包,里面添加了一个META-INF/spring.factories文件:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

那么,”customProperty“的PropertySource将会被包含到应用。

Environment改变

应用程序将监听EnvironmentChangeEvent,并且响应这一些改变(添加的ApplicationListeners可以被用户用标准的方式增加到@Beans)。EnvironmentChangedEvent观察到这些值被改变,会触发这些事情

  • 重新绑定@ConfigurationProperties bean到上下文
  • 根据logging.level.*来舍得属性的日志级别

默认情况下,Config Client不轮询Environment的改变。一般情况,不建议使用这种方式来监测变化(虽然你可以通过@Scheduled注解来设置)。对于可扩展的应用程序,使用广播EnvironmentChangeEvent到所有实例的方式,好过轮询的方式。(比如使用Spring Cloud Bus项目)。

修改Environment可以通过发布EnvironmentChangeEvent来做,这是Spring核心Api的方式。你可以通过观察/configprops端点(Spring Boot Actuator的特性)来检查这些改变绑定到@ConfigurationProperties的bean的情况。对于DataSource这样一个实例,在运行的时候修改maxPoolSize增加大小,修改的变化不会通知实例里面,可以使用@RefreshScope来初始化Bean。

@RefreshScope

一个Spring的@Bean在添加了@RefreshScope注解,可以解决Bean初始化的时候只能获得初始配置的问题。比如,在使用DataSource获得一个数据库连接的是时候,当通过Environment修改数据库连接字符串的时候,我们可以通过执行@RefreshScope俩根据修改的配置获取一个新的URL的连接。

@RefreshScope的beans,在使用它初始化的时候是延迟代理的。通过RefreshEndpoint Bean来控制。或者/refresh请求来重新初始化。

  • 注意 
    @RefreshScope注解在一个 @Configuration类上面,在重新初始化的时候需要注意到可以相互依赖造成的冲突。

加密和解密

Spring Cloud可以在本地进行预处理的解密,与Config Server有相同的规则,通过设置相同的`encrypt.*`来实现。因此,可以使用加密的值在`{cipher}*`上,在应用通过`Environment`获得属值之前进行解密。使用加密特性需要包含Spring Security RSA的包到classpath。Maven依赖”org.springframework.security:spring-security-rsa”。并且,需要在JVM添加JCE扩展。 如果使用Sun的JDK遇到`Illegal key size`异常,需要安装JCE 更多信息请查看:

提取文件到JDK/jre/lib/security文件夹(无论你使用的那个版本的JRE/JDK x64/x86)。

端点

相对于Spring Boot Actuator的应用,添加了一些管理端点:

  • POST to /env 更新Environment重新加载@ConfigurationProperties和日志级别
  • /refresh 重新初始化添加了@RefreshScope 的bean
  • /restart 重启初始化ApplicationContext,重启 (默认是禁用的)
  • /pause and /resume 调用ApplicationContext生命周期的方法stop()start()

通用的抽象Spring Cloud Commons

比如服务发现、负载平衡和断路器等通用的模型,本身是一个抽象层,可以被所有Spring Cloud组件独立的实现,例如服务发现有具体的实现Eureka、Consul。

Spring RestTemplate作为负载均衡客户端

RestTemplate 可以使用ribbon自动配置,简历一个负载均衡的RestTemplate使用@Bean@LoadBalanced来预设。

  • 警告 
    RestTemplate不会通过自动配置建立,必须单独配置。
复制代码
@Configuration
public class MyConfiguration {

    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

    public String doOtherStuff() {
        String results = restTemplate.getForObject("http://stores/stores", String.class);
        return results;
    }
}
复制代码

 

这里的URI需要使用虚拟主机名,比如服务名称,而不是Host名称。Ribbon客户端用它来建立一个完整的物理地址。可以查看`RibbonAutoConfiguration`的详细去设置`RestTemplate`。

多个RestTemplate对象

如果你希望创建一个未负载均衡的`RestTemplate`,可以用正常的方式来注意。访问负载均衡方式的`RestTemplate`使用`@LoadBalanced`来注解你建立的`@Bean`

复制代码
@Configuration
public class MyConfiguration {

    @LoadBalanced
    @Bean
    RestTemplate loadBalanced() {
        return new RestTemplate();
    }

    @Primary
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    @LoadBalanced
    private RestTemplate loadBalanced;

    public String doOtherStuff() {
        return loadBalanced.getForObject("http://stores/stores", String.class);
    }

    public String doStuff() {
        return restTemplate.getForObject("http://example.com", String.class);
    }
}
复制代码

 

  • 提示 
    如果你遇到了 
    java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89的错误提示,尝试使用 spring.aop.proxyTargetClass=true的代理方式注入。

忽略网络接口

有的时候,对于服务发现注册,忽略某些命名的网络接口是非常有用的,比如使用Docker容器的时候。可以通过一些规则设置来忽略这些网络接口,下面这个配置显示了忽略“docker0”的入口,所有的入口以“veth.*”来匹配。详细的配置类见`InetUtilsProperties`。

  • application.yml
spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - docker0
        - veth.*

 

Spring Cloud Config

Spring Cloud Config提供了在分布式系统的外部配置的客户端支持。通过配置服务(Config Server)来为所有的环境和应用提供外部配置的集中管理这些概念都通过Spring的EnvironmentPropertySource来抽象,所以它可以适用于各类Spring应用,同事支持任何语言的任何应用。它也能为你支持对应用开发环境、测试环境、生产环境的配置、切换、迁移。默认的配置实现通过git实现,同事非常容易的支持其他的扩展(比如svn等)。

快速开始

开始配置服务:

$ git clone https://github.com/spring-cloud/spring-cloud-config.git
$ cd spring-cloud-config
$ cd spring-cloud-config-server $ ../mvnw spring-boot:run

这是一个 Spring Boot应用,你可以在IDE里面通过ConfigServerApplication来启动。

可以看看效果:

$ curl localhost:8888/foo/development
{"name":"development","label":"master","propertySources":[ {"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}}, {"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}} ]}

默认通过git资源加载配置属性(使用spring.cloud.config.server.git.uri来配置git地址)。使用这些配置来初始化一个非常轻量的SpringApplication。这个应用的Environment加载属性通过返回JSON对象的请求。

  • 这些请求的Http资源下面这些
/{application}/{profile}[/{label}]
/{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.properties
  • application 根据spring.config.name来获得
  • profile 激活的剖面,比如spring.profiles.active = test
  • label git资源的label 默认是master

必须提供一个git资源,Spring Cloud Config Server才能从远程git服务pull资源来配置,例如:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo

 

客户端用法

配置服务一般作为单独的服务部署,各个需要的应用会添加一个客户来从配置服务获取配置。而配置服务的配置,依赖git提交的配置文件。

在Spring Boot应用里面,使用这个特性需要添加spring-cloud-config-client的依赖。比较方便是方式是添加一个Spring Boot的starter依赖org.springframework.cloud:spring-cloud-starter-config对于Maven用户,有一个spring-cloud-starter-parent的父pom文件。对于Gradle和Spring CLI用户,可以用Spring IO版本管理文件。下面是Maven配置:

  • pom.xml
<parent>
    <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- 上面版本可能依赖一些snapshots版本,添加spring的资源 --> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>http://repo.spring.io/milestone</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>

创建一个简单是Spring Boot的web应用:

@SpringBootApplication
@RestController
public class Application { @RequestMapping("/") public String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

 

当你运行的时候,这个应用默认启动8080端口,默认它会寻找本地的8888端口的配置服务。你可以修改bootstrap.properties文件配置服务的uri:

spring.cloud.config.uri: http://myconfigserver.com

启动加载的属性可以通过/env来查看,它有很高的优先级:

$ curl localhost:8080/env
{
  "profiles":[],
  "configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"}, "servletContextInitParams":{}, "systemProperties":{...}, ... }

一条属性是"configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"}里面的配置,它有最高优先级的。属性源中的 URL是git仓库的地址而不是配置服务器的URL。

配置服务服务端 Spring Cloud Config Server

Spring Cloud Config Server提供了一个基本Http的,资源API的,可扩展的配置(使用key-value的properties或者相似的yaml的方式)。通过添加@EnableConfigServer非常容易的嵌入到了Spring Boot应用里面。下面是一个配置服务的app:

  • ConfigServer.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServer { public static void main(String[] args) { SpringApplication.run(ConfigServer.class, args); } }

 

Spring Boot应用通常默认启动8080端口,Config Server通常切换到8888端口。在Config Server 的jar文件里面configserver.yml默认配置了spring.config.name=configserver,你可以在自己的配置文件里面修改。

  • application.properties
server.port: 8888
spring.cloud.config.server.git.uri: file://${user.home}/config-repo

 

${user.home}/config-repo 是一个git资源包含YAML文件和属性文件。

在Windows系统里面,如果文件URL是绝对路径,前面有驱动符号,你需要多增加个’/’符号, file:///${user.home}/config-repo.

  • 下面是在创建例如上面的Git仓库配方
$ cd $HOME
$ mkdir config-repo
$ cd config-repo
$ git init . $ echo info.foo: bar > application.properties $ git add -A . $ git commit -m "Add application.properties"

 

使用本地的git资源最好只用作测试使用,生产环境建议使用git服务器。

初始化配置的是非常高效快速的,当你使用特别大的二进制文件,可能会遇到第一个请求延迟的情况或者服务内存溢出的情况。

  • 补充 
    配置默认存储在tmp文件目录, linux系统默认会清理一定时间没有更新的tmp目录下的文件。生产环境上演出这一出悲剧。

资源库环境Environment Repository

Config Server的配置数据存储在哪里?

解决这个问题的是`EnvironmentRepository`,服务`Environment`对象。`Environment`对象是对Spring的Environment(其中包括 propertySources做为主要属性)的浅拷贝。Environment资源被参数化成了3个变量:

  • {application} 对应客户端的”spring.application.name”
  • {profile} 对应客户端的”spring.profiles.active”(逗号分隔)
  • {label} 服务端依赖的资源文件标记(比如git 的master)

配置库资源实现的表形式与Spring Boot的配置相关,比如{application}参数来自”spring.config.name”,{profiles}来自”spring.profiles.active”,profiles的优先级规则也和Spring Boot应用一样。激活的profiles的优先级高于默认的,有多个profiles,最后一个起作用。与Map的set操作类似。

例如:

  • bootstrap.yml
spring:
  application:
    name: foo
  profiles:
    active: dev,mysql

与Spring Boot应用程序一样,这些参数也可以通过环境变量或命令行参数进行设置。

如果配置库是基于文件的,服务器将优先根据foo.yml,在根据application.yml创建一个Environment对象如果这些 YAML文件中有指定了Spring profiles,那么这些profiles将有较高优先级,同时如果存在指定profile后缀YAML(或properties)文件,这些文件就比默认的文件具有更高的优先级。高优先级的配置优先转成Environment对象中的PropertySource。(这和单独的Spring Boot系统使用的规则是一样的)

 

后端的git

EnvironmentRepository默认情况下,通过依赖git服务来实现。git可以非常方便的修改升级配置,而且可以审查变更记录。可以在你的配置服务(比如application.yml文件)里面添加spring.cloud.config.server.git.uri配置指定git资源。你也可以直接使用file:前缀来配置一个本地资源,来快速开始你的服务。为了提高配置服务的高可用性和扩展性,你需要有指向同一个版本库服务器的所有实例,所以只有一个共享文件系统是可行的。即使在这种情况下,最好是使用ssh:协议共享文件系统存储库,以便服务器可以克隆它,并使用本地工作副本作为高速缓存。

这个资源的实现通过映射HTTP资源的{label}参数为git label(提交id,分支名称或tag)。如果git分支或tag的名称包含一个斜杠 (“/”),HTTP URL中的label需要使用特殊字符串”(_)”来替代(为了避免与URL的其他的参数路径混淆)。如果使用了命令行客户端如 curl,请谨慎处理URL中的括号(例如:在shell下请使用引号”来转义他们)。

Git URI占位符

Spring Cloud配置服务支持git资源的url使用 {application} 、 {profile}和 {label} 占位符。这的label指的是git的label。所以,你可以很容易的为每一个应用配置资源:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/myorg/{application}

 

或者,每一个资源一个{profile}的策略。

模式匹配和多个资源库

它还支持更复杂的规则使用applicationprofile来做模式匹配。这个模式的格式,试音逗号分隔的 {application}/{profile}列表作为通配符。

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          repos:
            simple: https://github.com/simple/config-repo
            special:
              pattern: special*/dev*,*special*/dev*
              uri: https://github.com/special/config-repo
            local:
              pattern: local* uri: file:/home/configsvc/config-repo

 

如果{application}/{profile}没有匹配到任何参数,它将默认使用的spring.cloud.config.server.git.uri定义的uri。在上面的例子中,simple资源匹配simple/*(匹配应用名字为simple的所有profile)。local资源匹配应用名称为local/*的所有的profile

注意,在上述”simple”的例子中,只使用一行来设置属性的便捷方式, 如果你需要设置其他属性(如credentials, pattern, etc.),你需要使用完整的格式才能表示清楚。

在配置里面的pattern属性实际上是一个数组,你可以使用YAML数组(属性文件里面使用[0]、[1])来绑定多个参数。你可能需要使用它,如果你用多个profiles来运行应用。

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          repos:
            development:
              pattern:
                - */development
                - */staging
              uri: https://github.com/development/config-repo
            staging:
              pattern:
                - */qa - */production uri: https://github.com/staging/config-repo

如果你的模式匹配参数不是以*结尾,又没有包含profile,Spring Cloud会推测匹配所有的profiles,比如*/staging["*/staging", "*/staging,*"]的简化写法。通常,在本地开发环境运行development的profile,在远程环境运行cloud的profile。

每个资源也可以选择在子目录存储配置文件,通过关键字searchPaths来查询定义的目录。例如:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          searchPaths: foo,bar*

在这个例子里面,服务会从foo/目录和以bar开头的目录查询配置文件。

默认情况下,当第一次请求的时候,服务clone远程资源。你也可以配置在启动的时候clone。

spring:
  cloud:
    config:
      server:
        git:
          uri: https://git/common/config-repo.git
          repos:
            team-a:
                pattern: team-a-*
                cloneOnStart: true uri: http://git/team-a/config-repo.git team-b: pattern: team-b-* cloneOnStart: false uri: http://git/team-b/config-repo.git team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git

在这个例子里面,服务启动的时候会clone team-a的配置,它是在接受到请求之前就进行的。其它资源则在资源第一次请求的时候clone。

远程配置的基础身份认证通过添加usernamepassword属性,例如:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          username: trolley
          password: strongpassword

如果你没有使用https和用户认证,也可以便捷的使用SSH,只需要将keys存储在默认的目录(~/.ssh),uri指向SSH地址(git@github.com:configuration/cloud-configuration)。服务使用JGit来访问你需要的任何配置文件。可以在~/.git/config下配置https代理,也可以使用JVM系统属性-Dhttps.proxyHost-Dhttps.proxyPort来配置。

如果你清楚你的~/.git目录,你可以使用git config --global来配置。比如:git config --global http.sslVerify false

查询占位符

Spring Cloud配置服务也支持查询路径使用 {application}{profile} (如果需要{label})占位符。比如:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          searchPaths: '{application}'

在与application相同名字的路径中查找配置库中的文件。在这里,通配符同样有效。

版本控制系统后端文件的使用

后面发现已经有翻译版本了:附上

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值