资讯动态

SpringCloud-Config 第5章 动态刷新配置(不停机更新)

发布时间:2026/10/15 16:12:36 来源:尧图企业网站定制
第5章 动态刷新配置不停机更新本章目标修改 Git 里的配置后不重启服务也能生效。5.1 问题背景默认情况下Client 只在启动时拉一次配置。之后你改了 Git 里的配置服务里的值不会变必须重启。动态刷新就是解决这个问题。5.2 方案一手动刷新单个服务步骤1加 Actuator 依赖第3章已加dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependency步骤2暴露 refresh 端点Client 的application.ymlmanagement:endpoints:web:exposure:include:refresh,health,info# 暴露 refresh 端点步骤3在需要刷新的 Bean 上加 RefreshScopeRestControllerRefreshScope// 关键注解标记此 Bean 的配置可被动态刷新publicclassConfigTestController{Value(${order.message})privateStringmessage;GetMapping(/config)publicStringshow(){returnmessagemessage;}}原理RefreshScope的 Bean 在收到 refresh 时会被销毁重建重建时重新注入最新配置值。步骤4触发刷新修改 Git 仓库里的order-service-dev.yml比如把 message 改掉并git commit发送 POST 请求触发刷新curl-X POST http://localhost:8081/actuator/refresh返回被刷新的 key 列表例如[order.message]再访问/config值已更新无需重启✅5.3 ConfigurationProperties 方式推荐比 Value 更优雅ConfigurationProperties绑定的 Bean 天然支持刷新不需要 RefreshScope但加了也无妨。ComponentConfigurationProperties(prefixorder)publicclassOrderProperties{privateStringmessage;// getter / setter 必须有publicStringgetMessage(){returnmessage;}publicvoidsetMessage(Stringmessage){this.messagemessage;}}使用RestControllerpublicclassOrderController{privatefinalOrderPropertiesprops;publicOrderController(OrderPropertiesprops){this.propsprops;}GetMapping(/msg)publicStringmsg(){returnprops.getMessage();}}调用/actuator/refresh后props.getMessage()自动是最新值。实战建议优先用ConfigurationProperties类型安全、支持校验、刷新友好。Value适合零散单个值。5.4 方案二批量刷新 —— Spring Cloud Bus消息总线手动刷新的问题有 100 个服务实例难道要调 100 次/actuator/refreshBus 用消息中间件RabbitMQ / Kafka广播刷新事件一次触发全部刷新。POST /actuator/busrefresh │ ▼ ┌─────────────────┐ │ 某个服务实例 │──┐ 发布刷新事件 └─────────────────┘ │ ▼ ┌──────────────┐ │ RabbitMQ │ 广播 └──────┬───────┘ ┌────────────────┼────────────────┐ ▼ ▼ ▼ 实例A(刷新) 实例B(刷新) 实例C(刷新)依赖以 RabbitMQ 为例dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-bus-amqp/artifactId/dependency配置 RabbitMQspring:rabbitmq:host:localhostport:5672username:guestpassword:guestmanagement:endpoints:web:exposure:include:busrefresh触发只需调一个实例curl-X POST http://localhost:8081/actuator/busrefresh所有连到同一个 RabbitMQ 的服务实例都会刷新 ✅5.5 方案三Git Webhook 自动刷新终极自动化配合 Spring Cloud Config Monitor Bus当你git push配置时Git 平台GitHub/GitLab通过 Webhook 回调 Config ServerServer 自动用 Bus 广播刷新。实现改配置→push→全自动生效无需任何手动调用。依赖spring-cloud-config-monitor暴露/monitor端点给 Git Webhook 调用。生产环境常用此方案。5.6 本章小结方案适用场景复杂度RefreshScope 手动 refresh单实例、学习⭐ConfigurationProperties推荐的配置绑定方式⭐Bus 总线 busrefresh多实例批量刷新⭐⭐Monitor Webhook生产全自动⭐⭐⭐ 下一章06-配置加密与安全.md

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑