本文介绍:环境仓库配置更新后,自动同步到配置客户端的原理。
以下通过一个实际案例展开分析,案例为:修改 Github 远程仓库路由配置后,路由转发功能实时生效。该案例构建于 peacetrue-microservice-template 项目(dev/1.1.0/config-sync 分支)。
使用配置同步,服务端需要添加:
客户端需要添加:
Figure 1. 原理概述
流程步骤说明:
PropertyPathEndpoint
接收配置变更通知RefreshRemoteApplicationEvent
RefreshRemoteApplicationEvent
刷新应用上下文查看接口网关路由配置信息:https://localhost/actuator/configprops
Figure 2. 路由配置信息
当前只有 /message
的路由。
因为在本地测试,Github 无法推送到本地,需要配置反向代理,这里使用到 ngrok 。
将 ngrok 映射到配置中心 8888 端口:
Figure 3. ngrok映射到配置中心
发现外网的 https 只能映射到内网的 http。这里需要改为映射到接口网关 443 端口:
Figure 4. ngrok映射到接口网关
这样外网的 https://cbd1194f0ddd.ngrok.io 就能访问到本地的 https://localhost:443 。Github 要将消息推送到配置中心,但无法直接访问配置中心,只能访问到接口网关,所以需要由接口网关转发到配置中心:
peacetrue-microservice-gateway.yml
spring:
cloud:
gateway:
routes:
#配置中心监听
- id: config_center_monitor
#配置中心地址
uri: ${MICROSERVICE_PROTOCOL:http}://${MICROSERVICE_CONFIG_HOST:localhost}:${MICROSERVICE_CONFIG_PORT:8888}/
predicates:
- Path=/monitor/**
因为配置中心启用了安全认证,直接访问 /monitor
接口会被拒绝,怎么处理呢?有两个办法:
/monitor
接口的认证http basic
认证WebSecurityConfig
@EnableWebSecurity
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
//第一种,直接忽略
web.ignoring().antMatchers("/monitor/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
//第二种,需要配置忽略 csrf
http.csrf(configurer -> configurer.ignoringAntMatchers("/monitor/**"));
}
}
Github Webhook 配置步骤如下:
最终进入 webhook 管理页,页面内容如下:
Figure 5. 配置GithubWebhook.png
页面各项解释如下:
application/json
,选择 application/json
修改远程仓库配置信息:
peacetrue-microservice-gateway.yml
spring:
cloud:
gateway:
routes:
#添加测试路由,拦截以 baidu4 起始的路径,转发到百度
- id: test4
uri: https://www.baidu.com/
predicates:
- Path=/baidu4/**
filters:
- RewritePath=/baidu4,/
提交并推送到 Github 后,webhook 管理页会显示此次操作后触发的请求信息:
Figure 6. github推送信息
试了很多次都不成功,主要是 ngrok 的代理会比较慢,总是请求超时:
Figure 7. webhook请求超时
实际上已经推送成功了,访问 https://cbd1194f0ddd.ngrok.io/baidu4 :
Figure 8. 访问百度
1. 使用 http basic 认证,加入用户名和密码
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。