SpringCloud - @RefreshScope 原理及使用

Spring Cloud @RefreshScope 原理及使用

https://www.cnblogs.com/javastack/p/12049139.html

RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一种特殊的scope实现,用来实现配置、实例热加载

 

Singleton和Prototype是硬编码的,并不是Scope子类。 Scope实际上是自定义扩展的接口

protected <T> T doGetBean(...){ final RootBeanDefinition mbd = ... if (mbd.isSingleton()) { ... } else if (mbd.isPrototype()) ... } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {...}); ... } ... }

Scope Bean实例交由Scope自己创建,例如SessionScope是从Session中获取实例的,ThreadScope是从ThreadLocal中获取的,而RefreshScope是在内建缓存中获取的

 

@Scope 的注册 AnnotatedBeanDefinitionReader#registerBean

public void registerBean(...){

 ...

  ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);

  abd.setScope(scopeMetadata.getScopeName());

 ...

  definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);

}

 

RefreshScope 刷新过程

入口在 ContextRefresher#refresh

refresh() { Map<String, Object> before = ①extract(this.context.getEnvironment().getPropertySources()); ②addConfigFilesToEnvironment(); Set<String> keys = ④changes(before,③extract(this.context.getEnvironment().getPropertySources())).keySet(); this.context.⑤publishEvent(new EnvironmentChangeEvent(keys)); this.scope.⑥refreshAll(); }

①提取标准参数(SYSTEM,JNDI,SERVLET)之外所有参数变量

②把原来的Environment里的参数放到一个新建的Spring Context容器下重新加载,完事之后关闭新容器

③提起更新过的参数(排除标准参数)

④比较出变更项

⑤发布环境变更事件,接收:EnvironmentChangeListener/LoggingRebinder

⑥RefreshScope用新的环境参数重新生成Bean,重新生成的过程很简单,清除refreshscope缓存幷销毁Bean,下次就会重新从BeanFactory获取一个新的实例(该实例使用新的配置)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值