SpringCloud中使用Apollo实现动态刷新
SpringCloud中使用Apollo实现动态刷新
普通字段
在需要刷新的字段上使用@value
注解即可,例如:
bean使用@ConfigurationProperties动态刷新
bean使用@ConfigurationProperties注解目前还不支持自动刷新,得编写一定的代码实现刷新。目前官方提供2种刷新方案:
- 基于RefreshScope实现刷新
- 基于EnvironmentChangeEvent实现刷新
方法一:基于RefreshScope实现刷新
- 确保项目中已引入依赖
- 实体类上使用
@RefreshScope
注解
在namespace=config的命名空间中定义配置:
- 利用RefreshScope搭配@ApolloConfigChangeListener监听实现bean的动态刷新
@ApolloConfigChangeListener(value="config")
表示监听namespace=config的配置文件的变化refreshScope.refresh("testUserProperties");
表示如果触发监听事件,则刷新名为testUserProperties
的bean;PrintChangeKeyUtils.printChange(changeEvent);
表示打印发送变化的熟悉(可选),PrintChangeKeyUtils
定义为:
方法二:基于EnvironmentChangeEvent实现刷新
- 定义实体类
与方法一的差异是不使用@RefreshScope
注解
- 利用spring的事件驱动配合@ApolloConfigChangeListener监听实现bean的动态刷新:
两种方式动态刷新原理浅析:
RefreshScope
首先了解Spring中几个相关的类:
- 注解@RefreshScope(
org.springframework.cloud.context.config.annotation.RefreshScope
)
- 注解@Scope(
org.springframework.context.annotation.Scope
)
- 接口Scope(
org.springframework.beans.factory.config.Scope
)
- 类RefreshScope(
org.springframework.cloud.context.scope.refresh.RefreshScope
)
带有@RefreshScope
注解后的Bean,在初始话的过程中,会通过AnnotationScopeMetadataResolver#resolveScopeMetadata
提取元数据:
可以理解为 @RefreshScope
是scopeName="refresh"的 @Scope
,其Bean的注册将通过AnnotatedBeanDefinitionReader#registerBean
完成的:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2022-04-21 mybatis all elements are null
2022-04-21 mac安装配置maven
2016-04-21 在多线程中使用静态方法是否有线程安全问题
2016-04-21 多线程并发
2016-04-21 消息中间件的技术选型心得-RabbitMQ、ActiveMQ和ZeroMQ
2016-04-21 通过RealProxy实现AOP
2016-04-21 分布式事物嵌套事物