Spring cloud config 实例

一.简介

Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring Environment和PropertySource抽象相同,因此它们与Spring应用程序非常契合,但可以与任何以任何语言运行的应用程序一起使用。随着应用程序通过从开发人员到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具。很容易添加替代实现,并使用Spring配置将其插入。

以上是官方解释,感觉太官方,说白了就是使配置和项目解耦
大体结构如下:
结构图

说白了就是服务端链接git仓库,客户端连接服务端

二.实例

1.服务端

本文讲述的是添加到EUREKA中的spring cloud config,不使用EUREKA的没啥大区别,就配置文件有一丢丢差异。
首先创建服务端项目service-config-server

    步骤:

     1. 添加pom
     2. 启动类添加注解
     3. 添加主配置文件(properties,yml)

添加pom

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

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

    <name>service-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.7.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>
        <spring-cloud.version>Dalston.SR3</spring-cloud.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>
        <!-- 身份验证security -->
        <!-- <dependency> -->
        <!-- <groupId>org.springframework.boot</groupId> -->
        <!-- <artifactId>spring-boot-starter-security</artifactId> -->
        <!-- <version>1.5.3.RELEASE</version> -->
        <!-- </dependency> -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

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

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</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>


</project>

主要是spring-cloud-config-server依赖,spring-cloud-starter-bus-amqp是用来实现自动更新配置的,不需要的可以不用,它有个方法/bus/refresh 试下批量更新配置节点,不过需要把项目配置上rabbitmq

启动类添加注解

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class ServiceConfigServerApplication {

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

@EnableConfigServer 代表config服务端

添加主配置文件(properties,yml)
application.properties

spring.application.name=config-server
server.port=3333
spring.application.index=${random.long}

#防止验证401
management.security.enabled=false

#通配符
spring.cloud.config.server.git.uri=http://pagit.paic.com.cn/serviceBot/{application}-config.git
#包括该目录下的配置文件
spring.cloud.config.server.git.searchPaths=dev,prd
#启动的时候就把资源文件下载下来,默认是首次请求才下载
#spring.cloud.config.server.git.clone-on-start=true
#spring.cloud.config.server.git.username=HAGA_HERO
#spring.cloud.config.server.git.password=111111


#          uri: https://gitlab.xxx.com/xxxxx/xxxxx.git     # 配置gitlab仓库的地址,注意,此处必须以.git结尾  
#          search-paths: /config-repo # gitlab仓库地址下的相对地址,可以配置多个,用,分割。  
#          username: your username                                             # gitlab仓库的账号  
#          password: your password

#加密因子,加密解密--对称加密
#encrypt.key=foo


#security.basic.enabled=true  安全认证
#security.user.name=HERO
#security.user.password=HERO

eureka.instance.preferIpAddress=true
eureka.client.serviceUrl.defaultZone=http://localhost:2222/eureka/

解释下哈:
spring.cloud.config.server.git.uri=http://pagit.paic.com.cn/serviceBot/{application}-config.git
是git仓库的地址
{application} 是通配符,也就是客户端spring.application.name是什么就替换成什么
spring.cloud.config.server.git.searchPaths 是包含git中的目录,例如
这里写图片描述
默认只会读取到根路径 application.properties
加上后就可以读取到dev,prd路径下的文件了

其他的没什么重要的了,感兴趣的可以研究下

运行测试
因为还没有客户端,就先把通配符去掉,改成
spring.cloud.config.server.git.uri=http://pagit.paic.com.cn/serviceBot/service-config.git
访问 http://localhost:3333/application-default.properties
或者http://localhost:3333/application-prd.properties
就可以看到文件中的内容

官方给的具体访问策略如下:
HTTP服务具有以下格式的资源:

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
2.客户端

首先创建服务端项目service-config-server

    步骤:

     1. 添加pom
     2. 添加主配置文件(properties,yml)
     3. 测试类

添加pom

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

    <groupId>com.example</groupId>
    <artifactId>service-config-client-bus-refresh</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.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>
        <spring-cloud.version>Dalston.SR3</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <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>

        <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>${spring-cloud.version}</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>


</project>

主要是spring-cloud-starter-config依赖,说明是config客户端。
spring-boot-starter-actuator依赖中有/refresh接口来刷新当前节点
其他的就没啥好说的了

添加主配置文件(properties,yml)
这里用到了application.properties 和bootstrap.yml
bootstrap.yml是在资源加载前就加在,在application.properties 之前。
因为链接服务端的配置如果写在application.properties 中有可能不加载、

application.properties

server.port=3335
#防止验证401
management.security.enabled=false

bootstrap.yml

#不结合eureka      
#spring:
#  application:
#    name: config-client    # 对应microservice-config-server所获取的配置文件的{application}
#  cloud:
#    config:
#      uri: http://localhost:3333/       # uri: http://yang:yang@localhost:3333/   链接需要认证的server
##      username: yang                   #优先级更高
##      password: yang
#      profile: dev                      # 指定profile,对应microservice-config-server所获取的配置文件中的{profile} 
#      label: master                     # 指定git仓库的分支,对应microservice-config-server所获取的配置文件的{label}     
#      

spring:
  cloud:
    config:
      discovery:
        enabled: true
        service-id: config-server 
      profile: dev
      label: master

  application:
    name: service     # 对应service-config-server所获取的配置文件的{application}
    index: ${random.long} #解决 多实例相同端口的话,就只刷新一个端口,用index区分下
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:2222/eureka/
  instance:
    prefer-ip-address: true

注解已经很清楚了,就不挨个解释了

测试类

@RestController
@RefreshScope
public class ConfigClientController {
    @Value("${profile}")
    private String profile;

    @GetMapping("/hello")
    public String hello() {
        return this.profile;
    }

}

profile是写在git中application.properties中的,也就是上图中的文件里。这样就根据配的不同的

  • profile: dev
  • label: master
  • name: service
    来加载不同的配置文件

    测试:修改profile的值后,push到githou 调用http://localhost:3335/refresh来刷新该节点客户端,或者调用http://localhost:3333/bus/refresh?destination = service:3335来刷新该节点客户端,或者调用http://localhost:3333/bus/refresh?destination = service来刷新该服务的所有节点客户端。
    

    刷新完后再次访问测试接口,返回值变成最新的了,这样就实现不需要重启应用就可以更改配置了。


总结
要想实现不需要动态加载,不需要手动执行刷新接口,需要连接MQ,之后把http://localhost:3333/bus/refresh?destination = service的url绑定到git仓库的设置中,设置成push完成后就调用url,gitlab貌似不支持,不过码云,github应该是支持的,想玩的可以试试。
个人觉得动态刷新不太实用,对于大多数项目来说,频繁改动的配置没有太多。不过对于大型项目来说,还是很有用的,例如:双11期间,增加下容量,还是很方便的,中小型项目就算了吧,不够费劲的,还增加了维护成本。还有一个好处就是,微服务架构中,每个模块都是一个项目,每个项目都有一堆配置,这样把他们放在一个项目中进行管理,比较方便。总之,看你心情喽^^

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值