原文地址:Spring Cloud 入门 之 Config 篇(六)

博客地址:http://www.extlight.com

一、前言

随着业务的扩展,为了方便开发和维护项目,我们通常会将大项目拆分成多个小项目做成微服务,每个微服务都会有各自配置文件,管理和修改文件起来也会变得繁琐。而且,当我们需要修改正在运行的项目的配置时,通常需要重启项目后配置才能生效。

上述的问题将是本篇需要解决的问题。

二、介绍

2.1 简单介绍

Spring Cloud Config 用于为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,它分为服务端和客户端两部分。服务端(config server)也称为分布式配置中心,是一个独立的微服务应用,用来连接配置仓库并为客户端提供获取配置信息,加密/解密信息等访问接口。而客户端(config client)则是微服务架构中各微服务应用或基础设施,通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。

2.2 运行原理

如上图,当 Config Client 首次启动时会向 Config Server 获取配置信息,Config Server 接收到请求再从远程私有仓库获取配置(连接不上项目会报错),并保存到本地仓库中。

当 Config Client 再次启动时会向 Config Server 获取配置信息,Config Server 还是会先从远程私有仓库拉去数据。如果网络问题或认证问题导致无法连接远程私有库,Config Server 才会从本地仓库获取配置信息返回给 Config Client。

三、Config 实战

本次实战基于 Eureka 篇的项目进行扩展演练。不清楚的读者请先转移至 《Spring Cloud 入门 之 Eureka 篇(一)》 进行浏览。

我们使用配置中心来维护 order-server 的配置数据(application.yml)。

测试场景:由于配置中心服务本身也是一个微服务,因此我们需要将配置中心注册到 Eureka 上,当 order-server 启动时先向 Eureka 获取配置中心的访问地址,然后从配置中心获取相应的配置信息进行正常启动。

本篇实战用到的项目列表:

服务实例 端口 描述
eureka-server 9000 注册中心(Eureka 服务端)
config-server 10000 配置中心(Eureka 客户端、Config 服务端)
order-server 8100 订单服务(Eureka 客户端、Config 客户端)

3.1 上传配置

在 GitHub 上新建一个私有仓库,名为 spring-cloud-config。

我们将 order-server 项目的配置文件放到改仓库中,如下图:

新建 2 个 yml 文件,内容为:

server:
port: 8100
eureka:
instance:
instance-id: order-api-8100
prefer-ip-address: true # 访问路径可以显示 IP
env: dev

ORDER-dev.yml 和 ORDER-test.yml 不同之处在于 env 的值,其中一个是 dev ,另一个是 test。

3.2 config 服务端

新建一个 spring boot 项目,名为 config-server(任意名字)。

  1. 添加依赖:
<dependencies>
<!-- eureka 客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> <!-- config 服务端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
  1. application.yml
server:
port: 10000 spring:
application:
name: CONFIG
cloud:
config:
server:
git:
uri: https://github.com/moonlightL/spring-cloud-config.git
username: moonlightL
password: xxx
basedir: d:/data # 本地库目录
eureka:
instance:
instance-id: config-api
client:
service-url:
defaultZone: http://localhost:9000/eureka/ # 注册中心访问地址
  1. 启动类添加 @EnableConfigServer:
@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigApplication { public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}

启动成功后,我们打开浏览器访问 http://localhost:10000/order-dev.ymlhttp://localhost:10000/order-test.yml,结果如下图:

config-server 服务成功拉去远程私有仓库的配置数据。

其中,访问规则如下:

<IP:PORT>/{name}-{profiles}.yml
<IP:PORT>/{label}/{name}-{profiles}.yml

name:文件名,可当作服务名称

profiles: 环境,如:dev,test,pro

lable: 分支,指定访问某分支下的配置文件,默认拉去 master 分支。

3.3 config 客户端

在 order-server 项目中。

  1. 添加依赖:
<!-- config 客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
  1. 删除 application.yml,并新建 bootstrap.yml,保存如下内容:
spring:
application:
name: ORDER
cloud:
config:
discovery:
enabled: true
service-id: CONFIG # config-server 在注册中心的名称
profile: dev # 指定配置文件的环境
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/ # 注册中心访问地址

配置中,通过 spring.cloud.config.discovery.service-id 确定配置中心,再通过 spring.application.name 的值拼接 spring.cloud.config.profile 的值,从而确定需要拉去从配置中心获取的配置文件。(如:ORDER-dev)

注意:必须保留 eureka 注册中心的配置,否则 order-server 无法连接注册中心,也就无法获取配置中心(config-server)的访问信息。

  1. 测试

新建一个测试类:

@RestController
@RequestMapping("/test")
public class TestController { @Value("${env}")
private String env; // 从配置中心获取 @RequestMapping("/getConfigInfo")
public String getConfigInfo() {
return env;
}
}

打开浏览器访问 http://localhost:8100/test/getConfigInfo,结果如下图:

成功获取 config-server 从远程私有仓库拉去的数据,由于在 bootstrap.yml 中配置了 spring.cloud.config.profile=dev,因此拉取到的数据就是 ORDER-dev.yml 中的数据。

引申问题:

当我们修改远程私有仓库的配置文件时,Config Server 如何知道是否该重新获取远程仓库数据呢?

现在已知唯一的解决方式就是重启 Config Client 项目,在项目启动时会请求 Config Server 重新拉去远程私有仓库数据。但是,如果是在生产环境下随便重启项目必定会影响系统的正常运行,那有没有更好的方式解决上述的问题呢?请读者继续阅读下文。

四、整合 Bus

Spring Cloud Bus 是 Spring Cloud 家族中的一个子项目,用于实现微服务之间的通信。它整合 Java 的事件处理机制和消息中间件消息的发送和接受,主要由发送端、接收端和事件组成。针对不同的业务需求,可以设置不同的事件,发送端发送事件,接收端接受相应的事件,并进行相应的处理。

4.1 配置中心

在 config-server 项目中:

  1. 添加依赖:
<!-- bus -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  1. 修改 application.yml,添加如下配置:
server:
port: 10000 spring:
application:
name: CONFIG
cloud:
config:
server:
git:
uri: https://github.com/moonlightL/spring-cloud-config.git
username: moonlightL
password: shijiemori960
rabbitmq:
host: 192.168.2.13
port: 5672
username: light
password: light eureka:
instance:
instance-id: config-api
client:
service-url:
defaultZone: http://localhost:9000/eureka/ # 注册中心访问地址 management:
endpoints:
web:
exposure:
include: "*" # 暴露接口

添加了 rabbitmq 配置和 management 的配置。

4.2 订单服务

在 order-server 项目中:

  1. 添加依赖:
<!-- bus -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  1. 修改 bootstrap.yml:
spring:
application:
name: ORDER
cloud:
config:
discovery:
enabled: true
service-id: CONFIG # config-server 在注册中心的名称
profile: dev # 指定配置文件的环境
rabbitmq:
host: 192.168.2.13
port: 5672
username: light
password: light
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/ # 注册中心访问地址

添加 rabbitmq 配置。

  1. 获取数据的类上添加 @RefreshScope 注解:
@RestController
@RequestMapping("/test")
@RefreshScope
public class TestController { @Value("${env}")
private String env; // 从配置中心获取 @RequestMapping("/getConfigInfo")
public String getConfigInfo() {
return env;
}
}

整合 Bus 后的原理图如下:

当我们修改远程私有仓库配置信息后,需要向 Config Server 发起 actuator/bus-refresh 请求。然后, Config Server 会通知消息总线 Bus,之后 Bus 接到消息并通知给其它连接到总线的 Config Client。最后,Config Client 接收到通知请求 Config Server 端重新访问远程私有仓库拉去最新数据。

  1. 测试:

修改远程私有仓库配置文件,使用 Postman 发起 POST 请求 http://localhost:10000/actuator/bus-refresh,最终配置中心重新拉去数据,最后再访问 order-server http://localhost:8100/test/getConfigInfo 获取最新数据,运行结果如下图:

如上图,我们实现了在不重启项目的情况下,获取变更数据的功能。

引申问题:

每次更新私有仓库中的配置文件都需要手动请求 actuator/bus-refresh,还是不够自动化。

下边我们来解决该问题。

五、集成 WebHook

远程私有仓库的提供 WebHook 配置,我们将 actuator/bus-refresh 配置上去,当远程私有仓库中的配置信息发生变动时,就会自动调用该接口最终实现自动刷新目的。

5.1 配置 WebHook 地址

登录 GitHub,点击 GitHub 的 WebHook 菜单,右侧面板中 Payload URL 填写 <配置中心 url>/actuator/bus-refresh, Content-type 选择 applicaton/json,保存即可。

由于笔者是本地测试,没有外网域名,因此借助 https://natapp.cn 做外网映射(操作简单,详情看官网教程),以下是笔者的外网信息:

设置 WebHook 操作如下图:

5.2 测试

预期效果:当我们修改 GitHub 上私有仓库的配置数据后,我们再访问 http://localhost:8100/test/getConfigInfo 应该展示最新的数据。

但是结果失败了。

原因:

回到 config-server 控制台查看日志发现报错了:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 68] (through reference chain: java.util.LinkedHashMap["hook"])]

这是因为,GitHub 在调用 <配置中心 url>/actuator/bus-refresh 时,往请求体添加了 payload 数据,但它不是一个标准的 JSON 数据。因此,config-server 在接收 GitHub 发送的请求获取,从请求体数据做转换时就报错了。

解决方案:

在 config-server 项目中,新建一个过滤器,用于过滤 actuator/bus-refresh 请求,将其请求体置空:

@Component
public class WebHookFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException { } @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String url = new String(httpServletRequest.getRequestURI()); // 只过滤 /actuator/bus-refresh 请求
if (!url.endsWith("/actuator/bus-refresh")) {
chain.doFilter(request, response);
return;
} // 使用 HttpServletRequest 包装原始请求达到修改 post 请求中 body 内容的目的
CustometRequestWrapper requestWrapper = new CustometRequestWrapper(httpServletRequest); chain.doFilter(requestWrapper, response); } @Override
public void destroy() { } private class CustometRequestWrapper extends HttpServletRequestWrapper {
public CustometRequestWrapper(HttpServletRequest request) {
super(request);
} @Override
public ServletInputStream getInputStream() throws IOException {
byte[] bytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); return new ServletInputStream() {
@Override
public boolean isFinished() {
return byteArrayInputStream.read() == -1 ? true : false;
} @Override
public boolean isReady() {
return false;
} @Override
public void setReadListener(ReadListener readListener) { } @Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
}
}

完成如上配置后,再次测试,结果如下:

搞定! 由于网络问题,拉去最新数据时有点慢,需要多刷新几次。。。

六、案例源码

config demo 源码

Spring Cloud 入门 之 Config 篇(六)的更多相关文章

  1. Spring Cloud 入门 之 Zuul 篇(五)

    原文地址:Spring Cloud 入门 之 Zuul 篇(五) 博客地址:http://www.extlight.com 一.前言 随着业务的扩展,微服务会不对增加,相应的其对外开放的 API 接口 ...

  2. Spring Cloud 入门 之 Hystrix 篇(四)

    原文地址:Spring Cloud 入门 之 Hystrix 篇(四) 博客地址:http://www.extlight.com 一.前言 在微服务应用中,服务存在一定的依赖关系,如果某个目标服务调用 ...

  3. Spring Cloud 入门 之 Eureka 篇(一)

    原文地址:Spring Cloud 入门 之 Eureka 篇(一) 博客地址:http://www.extlight.com 一.前言 Spring Cloud 是一系列框架的有序集合.它利用 Sp ...

  4. Spring Cloud 入门 之 Feign 篇(三)

    原文地址:Spring Cloud 入门 之 Feign 篇(三) 博客地址:http://www.extlight.com 一.前言 在上一篇文章<Spring Cloud 入门 之 Ribb ...

  5. Spring Cloud 入门 之 Ribbon 篇(二)

    原文地址:Spring Cloud 入门 之 Ribbon 篇(二) 博客地址:http://www.extlight.com 一.前言 上一篇<Spring Cloud 入门 之 Eureka ...

  6. Spring Cloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务

    首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入ho ...

  7. spring cloud 入门系列:总结

    从我第一次接触Spring Cloud到现在已经有3个多月了,当时是在博客园里面注册了账号,并且看到很多文章都在谈论微服务,因此我就去了解了下,最终决定开始学习Spring Cloud.我在一款阅读A ...

  8. Spring Cloud 入门教程 - 搭建配置中心服务

    简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...

  9. Spring Cloud 入门教程(七): 熔断机制 -- 断路器

    对断路器模式不太清楚的话,可以参看另一篇博文:断路器(Curcuit Breaker)模式,下面直接介绍Spring Cloud的断路器如何使用. SpringCloud Netflix实现了断路器库 ...

随机推荐

  1. BZOJ1300 [LLH邀请赛]大数计算器

    一开始以为暴力搞,后来看了数据范围还以为要FFT,各种被虐,然后Orz Seter大神!!! 我只想到了前三位:a * b <=> 10^(log(a) + log(b)),于是把乘的数都 ...

  2. VS2010创建动态链接库(DLL)的方法

    1.第一步创建WIN32项目,选择DLL 2.第二步,创建你自己的DLL CPP文件和头文件,下面以两个简单的加减法函数为例子导出 然后编译生成即可.DLL文件在Debug或Release目录中 .d ...

  3. 快速切题 sgu 111.Very simple problem 大数 开平方 难度:0 非java:1

    111.Very simple problem time limit per test: 0.5 sec. memory limit per test: 4096 KB You are given n ...

  4. MinGW的gdb调试

        MinGW(Minimalist GNU for Windows)提供了一套简单方便的Windows下的基于GCC程序开发环境.MinGW收集了一系列免费的Windows是用的头文件和库文件: ...

  5. hdu 1013 过山车 匈牙利算法(代码+详细注释)

    过山车 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  6. 4K电视与4K显示器的选择

    目前主流的电脑显示器分辨率是1920x1080,也就是常说的FHD标准,不过在智能手机都开始朝2560x1440前进了,PC显示器显然还需要更进一步的强化,下一代的标准就是4K分辨率,也就是Utlra ...

  7. koa 核心源码介绍

    链接来源 Request,Context,Response  在代码运行之前就已经存在的 Request和Response自身的方法会委托到Context中. Context源码片段 var dele ...

  8. matlab reshape()、full()

    一.reshape() 对于这个函数,就是重构矩阵. (1)要求:重构前后的矩阵元素个数一致.如3*4矩阵可以重构成2*6,2*3*2等. (2)重构方法:先按列将矩阵转换为向量,然后在向量的基础之上 ...

  9. 开源库dlib的安装与编译-CMake

    前言 最近项目涉及到关于face alignment的实现,了解到目前主要的算法有ERT.SDM.LBF等,其中由于dlib开源库实现了ERT算法,效果也很不错,故开始研究dlib的使用.而使用的第一 ...

  10. chapter02 svm对手写体数字的数码图像进行识别

    #coding=utf8 # 从sklearn.datasets里导入手写体数字加载器. from sklearn.datasets import load_digits # 从sklearn.cro ...