阅读背景:

Spring Cloud Config学习总结

来源:互联网 

    Spring Cloud Config作为分布式系统的配置中心,Config Server默认从git上获取配置文件。当Spring应用启动时,会连接上Config Server,从Config Server获取配置来初始化Spring环境。

    一、创建git仓库

          1.1 创建远程git仓库

               Git创建公开仓库

               Config Server配置资源库

          1.2 创建本地git仓库

$ mkdir config-repo
$ cd config-repo
$ git init .
$ echo info.foo: bar > application.properties
$ git add -A .
$ git commit -m "Add application.properties"

在仓库中加如下格式的文件。

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

以上端点可以直接访问资源库的配置文件


比如我上面访问的就是第一种方式,省略的label,也就是master分支。

 application -》 Config Client的spring.application.name,要唯一指定,默认是application;

 profile -》Config Client的spring.profiles.active = config1,config2 ,或者spring.cloud.config.profile= config1,config2

 label -》Config Server的spring.cloud.config.label,默认是master分支,也可以是Tag分支名,commit id;多个以逗号分隔;

 注意:一定要commit,要不然Config Server启动时,会报如下错:

         

         原因是没有默认的master分支。


 二、创建Config Server

        启动类:

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

    application.properties:

spring.application.name=config-server
#默认是8080端口,为避免冲突,我们自定义一个
server.port=8889

#公开的远程git仓库
#spring.cloud.config.server.git.uri=https://github.com/bawcwchen/config/
#本地仓库
spring.cloud.config.server.git.uri=file:///D:/back/localgit
#按项目搜索配置文件
spring.cloud.config.server.git.searchPaths=app1,app2
spring.cloud.config.label=master
#spring.cloud.config.server.git.username=your username
#spring.cloud.config.server.git.password=your password

注意,如果spring.cloud.config.server.git.uri用的是windows系统的本地仓库,以file:///开头。

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cj</groupId>
    <artifactId>config-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>config-server</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>


</project>

三、 Config Client

        Config Client其实就是我们的分布式系统客户端应用。

        启动类:

        

@SpringBootApplication
@RestController
public class ConfigClientApplication {

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

    /**
     * config server连接的远程资源库和本地application.properties都提供
     * 优先取config server上配置app1-config1.properties
     * 若没有,则取application.properties配置
     */
    @Value("${username}")
    private String username;

    /**
     * config server没有提供该配置,取application.properties
     */
    @Value("${year}")
    private Integer year;

    /**
     * 取config server上配置app1-config2.properties,注意这里是资源库上另外一个配置文件
     */
    @Value("${address}")
    private String address;

    /**
     * 从application.properties, application.yml, application-*.properties取全局配置。
     */
    @Value("${greeting}")
    private String greeting;

    @RequestMapping(value = "/hello")
    public String hello() {
        return username + ":" + year + ":" + address + ":" + greeting;
    }
}

PS:

  git资源库上以application开头的配置文件,会被所有Config Client共享,自动获取该配置文件。如下:


  Config Client启动时,可能报错,因为从git仓库获取配置时,网络性能不好,多试几次就好了。

  application.properties:

server.port=8881

username = 张三
year = 18

#spring cloud配置,最好放到bootstrap.properties里,要不然有问题,
#比如:这里spring.cloud.config.uri不生效,还是去连接的默认的8888端口
#spring.cloud.config.label=master
#spring.cloud.config.profile= config1,config2  
#spring.cloud.config.uri= https://localhost:8889/

 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.forezp</groupId>
    <artifactId>config-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

 bootstrap.properties:

  这个文件是客户端应用启动的引导文件,里面的内容最好单独出来,不要放到application.properties里去,要不然会有一些莫名其妙的问题。

#这个配置项不要像纯springboot应用那样放到application.properties里,
#要不然启动时,如果application.properties没有配置项,会报找不到config server上的配置项
spring.application.name= app1

spring.cloud.config.label=master

#以下2种方式指定配置文件都行
#spring.cloud.config.profile= config1,config2
spring.profiles.active = config1,config2  //获取多配置文件

spring.cloud.config.uri= https://localhost:8889/


 当客户端启动时,它的正常启动日志如下这样:

2018-05-27 16:26:37.343  INFO 156880 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: https://localhost:8889/
2018-05-27 16:26:37.740  INFO 156880 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=app1, profiles=[config1, config2], label=master, version=4531e6fdf74c00fa9f122b8fe00bf437816dd786, state=null
2018-05-27 16:26:37.740  INFO 156880 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource [name='configService', propertySources=[MapPropertySource [name='configClient'], MapPropertySource [name='file:///D:/back/localgit/app1/app1-config2.properties'], MapPropertySource [name='file:///D:/back/localgit/app1/app1-config1.properties']]]

当客户端启动时,会连接到Config Server,Server的输出日志如下:


如果连接的是Git远程仓库,它会在本地的${user.home}\AppData\Local\Temp下仓库本地仓库。


PS:不用git仓库,直接从本地文件系统取配置。也可以从svn上取配置没试过。

Config Server配置修改如下:

spring.profiles.active=native
spring.cloud.config.server.native.searchLocations = file:///D:/back/localgit/app1,file:///D:/back/localgit/app2

Config Client配置修改如下:

#spring.cloud.config.label=master

因为不是git仓库,所以不用指定label了。

spring.cloud.config.server.native.searchLocations 也可以指定到[classpath:/, classpath:/config] 下。

访问地址:

https://localhost:8881/hello



项目源码地址:

https://github.com/bawcwchen/config-demo.git


分享到: