spring cloud config的使用

    在传统的应用中,我们的配置文件都是放在项目中,这个影响不大。但是在一个微服务架构的系统中,我们的微服务可能存在几十上百个,并且每个小的微服务可能又部署在多台机器上,那么这个时候如果我们的配置文件在都放在具体的微服务中,那么就不好进行维护了,因此我们需要将服务中的配置文件单独抽取出来,集中管理。spring cloud config 可以为我们做到配置的集中管理,动态刷新配置等。当然除了spring cloud config 还有其它的也可以实现配置的集中管理,此处简单的来看一下 spring cloud config 的配置。

 

实现功能

    1、config server 端的编写并注册到eureka上
    2、config server 端增加 basic 认证
    3、config server 路径查找,searchPaths 参数
    4、配置项进行对称加密处理
    5、其它的一些配置见具体的配置文件上
    6、客户端的快速失败
    7、config server 的一些加密和解密端点

 

注意:

     1、config server 和 config client 的配置文件都需要写在 bootstrap.yml 配置文件中

     2、启用配置加密时,需要从 oracle 官网下载 JCE ,并覆盖在 jdk/jre/lib/security 目录中

            |- Java 6 JCE

            |- Java 7 JCE

            |- Java 8 JCE

代码结构


 

配置文件的访问路径

config server端访问路径

   例如:http://configer_server:port/{application}-{profile}.properties

              http://localhost:8301/product-provider-config-client-8302-dev.properties

              {application}   --->  product-provider-config-client-8302

              {profile}           --->  dev

              {label}              --->  master 没有指定默认就是 master 分支(此处指的是git的分支)。

              即最终的配置的值product-provider-config-client-8302.propertiesproduct-provider-config-client-8302-dev.properties合并的值。

 

在 github 上创建一个仓库,作为配置存放的地方

 

配置服务器服务端编写

       1、config server端增加basic认证,需要引入 spring security

       2、由于引入了spring security 所以需要放行 /encrypt/status,/encrypt/**,/decrypt/** 这些端点,便于测试

       3、配置服务器的配置放置在 git 服务器上,如果是在私有仓库,那么需要配置 username和password的值

       4、默认情况下是第一次访问配置的时候从 git 服务器上 clone 下配置,修改成程序一启动就拉取配置

       5、指定 git 配置存在在本地的路径

       6、启用配置的对称加密

             |- encrypt.key 这个值必须配置bootstrap.yml 配置文件中,否则不生效

             |- 使用 post 访问 http://config_server_host:port/encrypt 请求body中放入 需要加密的字符串,访问得到加密的值。  server.port={cipher}459c0c93ceab39c1924bb5addf72f03dc5eedfed7edac44851ecb0a1a1e888c9

 

1、依赖的引入,主要引入 config server 和 spring security 的依赖


 

2、启动类上增加 @EnableConfigServer 注解

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

 

3、配置文件 bootstrap.yml 的编写


   此处启用加密,需要将上方注意事项中的 JCE 下载下来,并覆盖在
JDK/jre/lib/security 目录中

   加密后里面的配置的写法:

server:
  port: '{cipher}459c0c93ceab39c1924bb5addf72f03dc5eedfed7edac44851ecb0a1a1e888c9'

 

配置客户端的编写,即具体的微服务配置

1、依赖的引入,主要是 config

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

 

2、bootstrap/yml 配置文件的编写


 

配置及运行结果


 

完整代码

   config server 和 config client 演示代码: https://gitee.com/huan1993/spring-cloud-parent/tree/master/config

 

posted @ 2018-06-15 12:02  huan1993  阅读(42)  评论(0编辑  收藏  举报