Spring Cloud Config的目标是在在大量的微服务中,将服务配置信息和和服务的实际物理部署分离,且服务配置服务不应与服务实例一起部署。配置信息应该作为环境变量传递给正在启动的服务,或者在服务启动时从存储库(文件系统,Git)中读取。

下面,分别从个方面来讲Config:Config Server,Config Client,High availability Config Server,使用Spring Security保护Config Server,配置自动刷新。

(1)搭建Config Server

首先,在pom.xml中添加依赖spring-cloud-config-server。

  1. <!-- Spring cloud: config server -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-config-server</artifactId>
  5. </dependency>

其次,在启动类ServerConfigApplication中加入@EnableConfigServer注解。

  1. @SpringBootApplication
  2. @EnableConfigServer
  3. public class ServerConfigApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(ServerConfigApplication.class, args);
  6. }
  7. }

我们知道,Config Server是用来集中管理配置文件的地方,那么在哪存放这些配置文件呢?Config Server提供了两种方法,分别是Git Solution和Classpath and file-based solution。

(1.1)Git Solution

Git Solution就是把配置文件放到Git Repository中,下面代码使用HTTPS跳过SSL验证,使用username和password来连接Git Repository:

bootstrap.yml

  1. # bootstrap.yml用来程序引导时执行,应用于更加早期配置信息读取,如可以使用来配置application.yml中使用到参数等
  2. # bootstrap.yml先于application.yml加载
  3. spring:
  4. application:
  5. name: server-config
  6.  
  7. # 使用对称加密设置secret key(https://blog.csdn.net/u012702547/article/details/78499458)
  8. # curl http://{confgit server host}:{port}/server-config/encrypt -d {pass} (need remove security)
  9. encrypt:
  10. key: my-secret-key

application.yml

  1. # Git solution
  2. spring:
  3. cloud:
  4. config:
  5. server:
  6. git:
  7. uri: https://github.com/lyz170/spring-cloud-demo.git
  8. # https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_skipping_ssl_certificate_validation
  9. skipSslValidation: true
  10. # https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_placeholders_in_git_search_paths
  11. searchPaths: 'config/{application}'
  12. username: xxxxxxxx
  13. password: '{cipher}xxxxxxxxxxxxx'

我们可以看到,我们使用了一个叫spring-cloud-demo的repository,因为用了HTTPS访问,所以我们跳过SSL验证,通过查找仓库中config目录下的所有applications,使用username和password来连接Git Repository。这里的password使用了JCE加密,需要从Oracle官网上下载额外的jar包,如果不了解的话可以查阅相关资料。

关于更多的Git配置,可以查阅https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_git_backend

(1.2)Classpath and file-based solution

就是把配置文件全部放在项目中(这里是src/main/resources/config),通过classpath去读取:

bootstrap.yml

  1. spring:
  2. application:
  3. name: server-config

application.yml

  1. # Classpath and file-based solution
  2. spring:
  3. profiles:
  4. active: native
  5. cloud:
  6. config:
  7. server:
  8. native:
  9. searchLocations: classpath:config,classpath:config/app1,classpath:config/app2

无论是用(1.1)还是(1.2),目录和文件的命名都是有要求的。目录是spring.application.name的值,文件为{application}-{profile}.yml。假设有2个application(app1,app2),和2个环境(dev,prod),目录和文件的命名如下:

  1. config
  2. |--app1
  3. |--app1.yml
  4. |--app1-dev.yml
  5. |--app1-prod.yml
  6. |--app2
  7. |--app2.yml
  8. |--app2-dev.yml
  9. |--app2-prod.yml

[注] 启动时无论环境参数是dev还是prod,都会先读取默认的{app}.yml,然后用dev或prod中的参数覆盖默认的{app}.yml。所以,可以把一些共通的配置配到{app}.yml中,把需要改变或增加的配置配到相应的{app}-{profile}.yml中。

配置完成后,我们启动该服务,可以通过下面的格式看到配置文件的内容:

  1. http://{hostname}:{port}/{应用名}/{环境名}[/{分支名}]
  2. http://{hostname}:{port}/{应用名}-{环境名}.yml
  3. http://{hostname}:{port}/{分支名}/{应用名}-{环境名}.yml

例如:http://127.0.0.1:10010/server-config/app1/prod,http://127.0.0.1:10010/server-config/app1-dev.yml

(2) 搭建Config Client

先引入依赖包spring-cloud-starter-config。

  1. <!-- Spring cloud starter: config client -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-config</artifactId>
  5. </dependency>

在配置文件(bootstrap.yml)中添加配置,指定config server服务的位置。

  1. spring:
  2. application:
  3. name: app-db
  4. cloud:
  5. config:
  6. uri: http://localhost:10010/server-config

这样,在服务启动时,会根据参数[--spring.profiles.active={env}],去Config Server拿到相应环境的配置文件后,再启动项目。

(3) 搭建High availability Config Server

既然是高可用的,所以首先需要创建多个Config Server实例。然后这里有两种方式:Eureka Service Discovery和Multiple Urls。

(3.1)Eureka Service Discovery

这里使用了Spring Cloud Netflix and Eureka Service Discovery,即把所有Config Server作为Eureka Client注册Eureka Server中,再通过Eureka的Discovery,只需配置一个service-id即可连接多个Config Server。

如何把Config Server注册Eureka Server中不再赘述,可以去看Spring Cloud(3):服务发现(Eureka)的第2部分。配置好Eureka后,需要分别配置Config Server和Config Client。

Config Server - bootstrap.yml

  1. # If the Config Server is secured with HTTP Basic, you can configure the credentials as user and password.
  2. # Also, if the Config Server has a context path, you can set configPath.
  3. # http://cloud.spring.io/spring-cloud-static/Greenwich.RELEASE/single/spring-cloud.html#discovery-first-bootstrap
  4. eureka:
  5. instance:
  6. metadataMap:
  7. # user: xxxxxxxx
  8. # password: '{cipher}xxxxxxxx'
  9. configPath: /server-config

[注] 如果配置了server.servlet.ocntext-path,则需要配置configPath;如果使用了HTTP Basic,则要在这里配置认证信息。

Config Client - bootstrap.yml

  1. spring:
  2. application:
  3. name: app-db
  4. cloud:
  5. config:
    # 使用service-id代替url实现config高可用
  6. discovery:
  7. enabled: true
  8. serviceId: server-config

[注] 这里的service-id就是Config Server的application name,也是在Eureka Server中注册的application name。

在配置Config Client时,我们发现,配置Config Server的优先级很高,在bootstrap.yml中。然而,使用Discovery的方式必须在配置Config Server前配置好Eureka。这也就导致了bootstrap.yml中的配置过多,并且不能把这些配置配到Config Server中。在多环境中,我们还要在本地创建多个bootstrap-{profile}.yml。这个问题目前我还没有解决方法。

本部分参考:https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#discovery-first-bootstrap

(3.2)Multiple Urls

其实就是(2)中配置多个URL即可。

  1. spring:
  2. application:
  3. name: app-db
  4. cloud:
  5. config:
  6. uri: "http://localhost:10010/server-config,\
  7. http://127.0.0.1:10011/server-config,\
  8. http://127.0.0.1:10012/server-config"

需要说明的是,Config Client会逐个连接,只有在Config Server未运行时(即应用程序已退出时)或发生连接超时时,才能确保高可用性(即跳过当前url连接下一个url)。但是,如果Config Server返回500(内部服务器错误)响应或Config Client从Config Server收到401(由于凭据错误或其他原因),表示用户问题而不是可用性问题,则Config Client不会尝试去连接下一个url。

本部分参考:https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_specifying_multiple_urls_for_the_config_server

(4)使用Spring Security保护Config Server

首先,需要添加spring-cloud-starter-security依赖。

  1. <!-- Spring cloud starter: security -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-security</artifactId>
  5. </dependency>

然后,添加一个user和password用于登录即可。

  1. @EnableWebSecurity
  2. public class ServerConfigWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
  3.  
  4. @Bean
  5. public PasswordEncoder passwordEncoder() {
  6. return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  7. }
  8.  
  9. @Override
  10. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  11. //@formatter:off
  12. PasswordEncoder encoder = new BCryptPasswordEncoder();
  13. auth.inMemoryAuthentication()
  14. .withUser("config-user").password("{bcrypt}" + encoder.encode("config-user")).roles("USER");
  15. //@formatter:on
  16. }
  17. }

当Config Client连接时,如果使用了Eureka Service Discovery方式,只需在Config Server中添加如下配置:

  1. # 使用对称加密设置secret key(https://blog.csdn.net/u012702547/article/details/78499458)
  2. # curl http://{confgit server host}:{port}/server-config/encrypt -d {pass} (need remove security)
  3. encrypt:
  4. key: my-secret-key
  5.  
  6. # If the Config Server is secured with HTTP Basic, you can configure the credentials as user and password.
  7. # Also, if the Config Server has a context path, you can set configPath.
  8. # https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#discovery-first-bootstrap
  9. # 该配置只用于Eureka Service Discovery(spring.cloud.config.discovery.serviceId) 如果使用了Multiple Urls则不需要配置
  10. eureka:
  11. instance:
  12. metadataMap:
  13. user: xxxxxxxx
  14. password: '{cipher}xxxxxxxx'
  15. configPath: /server-config

如果使用了Url或Multiple Urls,可以在Config Client中这样写:

  1. encrypt:
  2. key: my-secret-key
  3.  
  4. config:
  5. username: xxxxxxxx
  6. password: '{cipher}xxxxxxxx'
  7.  
  8. spring:
  9. application:
  10. name: app-db
  11. cloud:
  12. config:
  13. uri: "http://${config.username}:${config.password}@localhost:10010/server-config,\
  14. http://${config.username}:${config.password}@127.0.0.1:10011/server-config,\
  15. http://${config.username}:${config.password}@127.0.0.1:10012/server-config"

(5)配置自动刷新

简要来说,就是使用@RefreshScope注解,然后客户端执行/refresh端点即可。这里省略。

Spring Cloud(3):配置服务(Config)的更多相关文章

  1. spring cloud 2.x版本 Config配置中心教程

    前言 本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 本文基于前面的文章eureka-server的实现. 参考 eureka-server ...

  2. Spring Cloud构建微服务架构:服务网关(路由配置)【Dalston版】

    转载:http://blog.didispace.com/spring-cloud-starter-dalston-6-2/ 原创  2017-08-26  翟永超  Spring Cloud 被围观 ...

  3. Spring Cloud构建微服务架构(一)服务注册与发现

    Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁 ...

  4. Spring Cloud Consul 实现服务注册和发现

    Spring Cloud 是一个基于 Spring Boot 实现的云应用开发工具,它为基于 JVM 的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布 ...

  5. Spring Cloud构建微服务架构(二)服务消费者

    Netflix Ribbon is an Inter Process Communication (IPC) cloud library. Ribbon primarily provides clie ...

  6. 使用Spring Cloud连接不同服务

    http://www.infoq.com/cn/articles/spring-cloud-service-wiring 主要结论 Spring Cloud为微服务系统中相互依赖的服务提供了丰富的连接 ...

  7. Spring Cloud构建微服务架构(五)服务网关

    通过之前几篇Spring Cloud中几个核心组件的介绍,我们已经可以构建一个简略的(不够完善)微服务架构了.比如下图所示: 我们使用Spring Cloud Netflix中的Eureka实现了服务 ...

  8. Spring Cloud构建微服务架构 - 服务网关

    通过之前几篇Spring Cloud中几个核心组件的介绍,我们已经可以构建一个简略的(不够完善)微服务架构了.比如下图所示: alt 我们使用Spring Cloud Netflix中的Eureka实 ...

  9. 基于Spring Cloud的微服务入门教程

    (本教程的原地址发布在本人的简书上:http://www.jianshu.com/p/947d57d042e7,若各位看官有什么问题或不同看法请在这里或简书留言,谢谢!) 本人也是前段时间才开始接触S ...

  10. 干货|基于 Spring Cloud 的微服务落地

    转自 微服务架构模式的核心在于如何识别服务的边界,设计出合理的微服务.但如果要将微服务架构运用到生产项目上,并且能够发挥该架构模式的重要作用,则需要微服务框架的支持. 在Java生态圈,目前使用较多的 ...

随机推荐

  1. vuex直接修改state 与 用commit提交mutation来修改state的差异

    一. 使用vuex修改state时,有两种方式: 1)可以直接使用 this.$store.state.变量 = xxx;  2)this.$store.dispatch(actionType, pa ...

  2. C# 泛型(4) 持续更新

    泛型可以创建独立于被包含类型的类和方法. C++模板与泛型相似. 泛型优点性能 System.Collections 和 System.Collections.Generic 名称空间泛型和非泛型集合 ...

  3. 【Android-数据库Sqlite】Sqlite数据库 增、删、改、查

    1.先创建一个Product类 Product.java 变量如下: int id; String code; String name; int qty; 2.创建一个DBHelper类 DBHelp ...

  4. 2019牛客暑期多校训练营(第一场)A题【单调栈】(补题)

    链接:https://ac.nowcoder.com/acm/contest/881/A来源:牛客网 题目描述 Two arrays u and v each with m distinct elem ...

  5. OSError: cannot open resource(pillow错误处理)

    https://www.jianshu.com/p/c64ae3e9b196 pillow使用备忘之OSError: cannot open resource错误处理 在使用pillow过程中,Pyt ...

  6. [Luogu] 相关分析

    不想调了 #include <bits/stdc++.h> ; #define LL long long #define gc getchar() int fjs; struct Node ...

  7. elastic search&logstash&kibana 学习历程(四)kibana安装部署和使用

    kibana在linux上的部署安装 运行环境是centos7 基于jdk8 下载安装包:wget https://artifacts.elastic.co/downloads/kibana/kiba ...

  8. Mybatis源码学习之日志(五)

    简述 在Java开发中常用的日志框架有Log4j.Log4j2.Apache Commons Log.java.util.logging.slf4j等,这些工具对外的接口并不相同.为了统一这些工具的接 ...

  9. Navicat Premium 12破解版激活(全新注册机)

    使用打包下载就可以了 打包下载:(注册机有5.0和5.1用哪个看心情,我用的5.1) 连接:https://pan.baidu.com/s/1ARjFa2vEYxe9sljbrZR8fQ 提取码:lx ...

  10. 为vue3.0学点typescript, 解读高级类型

    知识点摘要 本节课主要关键词为: 自动类型推断 / 类型断言 / 类型别名(type) / 映射类型(Pick/Record等...) / 条件类型(extends) / 类型推断(infer) 自动 ...