@RefreshScope那些事

@RefreshScope那些事

要說清楚RefreshScope,先要了解Scope

  • Scope(org.springframework.beans.factory.config.Scope)是Spring 2.0開始就有的核心的概念

  • RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一種特殊的scope實(shí)現(xiàn),用來實(shí)現(xiàn)配置、實(shí)例熱加載。

  • Scope -> GenericScope -> RefreshScope


    scope_hierarchy.jpeg
  • Scope與ApplicationContext生命周期

    • AbstractBeanFactory#doGetBean創(chuàng)建Bean實(shí)例
     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>() {...});
              ...
        }
        ...
     }
    
    • Singleton和Prototype是硬編碼的,并不是Scope子類。 Scope實(shí)際上是自定義擴(kuò)展的接口
    • Scope Bean實(shí)例交由Scope自己創(chuàng)建,例如SessionScope是從Session中獲取實(shí)例的,ThreadScope是從ThreadLocal中獲取的,而RefreshScope是在內(nèi)建緩存中獲取的。
  • @Scope 對(duì)象的實(shí)例化

    • @RefreshScope 是scopeName="refresh"的 @Scope
     ...
      @Scope("refresh")
      public @interface RefreshScope {
          ...
      }
    
    • @Scope 的注冊(cè) AnnotatedBeanDefinitionReader#registerBean
      public void registerBean(...){
        ...
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
          abd.setScope(scopeMetadata.getScopeName());
        ...
          definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
      }
    
    • 讀取@Scope元數(shù)據(jù), AnnotationScopeMetadataResolver#resolveScopeMetadata
    public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
              AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
                      annDef.getMetadata(), Scope.class);
              if (attributes != null) {
                  metadata.setScopeName(attributes.getString("value"));
                  ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
                  if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
                      proxyMode = this.defaultProxyMode;
                  }
                  metadata.setScopedProxyMode(proxyMode);
              }
    }
    
    • Scope實(shí)例對(duì)象通過ScopedProxyFactoryBean創(chuàng)建,其中通過AOP使其實(shí)現(xiàn)ScopedObject接口,這里不再展開

現(xiàn)在來說說RefreshScope是如何實(shí)現(xiàn)配置和實(shí)例刷新的

  • RefreshScope注冊(cè)

    • RefreshAutoConfiguration#RefreshScopeConfiguration
      @Component
      @ConditionalOnMissingBean(RefreshScope.class)
      protected static class RefreshScopeConfiguration implements BeanDefinitionRegistryPostProcessor{
      ...
          registry.registerBeanDefinition("refreshScope",
          BeanDefinitionBuilder.genericBeanDefinition(RefreshScope.class)
                              .setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
                              .getBeanDefinition());
      ...
      }
    
    • RefreshScope extends GenericScope, 大部分邏輯在 GenericScope 中
    • GenericScope#postProcessBeanFactory 中向AbstractBeanFactory注冊(cè)自己
    public class GenericScope implements Scope, BeanFactoryPostProcessor...{
          @Override
          public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
              throws BeansException {
              beanFactory.registerScope(this.name/*refresh*/, this/*RefreshScope*/);
              ...
          }
    }
    
  • 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.⑥r(nóng)efreshAll();
     }
    
    • ①提取標(biāo)準(zhǔn)參數(shù)(SYSTEM,JNDI,SERVLET)之外所有參數(shù)變量
    • ②把原來的Environment里的參數(shù)放到一個(gè)新建的Spring Context容器下重新加載,完事之后關(guān)閉新容器
    • ③提起更新過的參數(shù)(排除標(biāo)準(zhǔn)參數(shù))
    • ④比較出變更項(xiàng)
    • ⑤發(fā)布環(huán)境變更事件,接收:EnvironmentChangeListener/LoggingRebinder
    • ⑥RefreshScope用新的環(huán)境參數(shù)重新生成Bean
    • 重新生成的過程很簡(jiǎn)單,清除refreshscope緩存幷銷毀Bean,下次就會(huì)重新從BeanFactory獲取一個(gè)新的實(shí)例(該實(shí)例使用新的配置)
    • RefreshScope#refreshAll
      public void refreshAll() {
              <b>super.destroy();</b>
              this.context.publishEvent(new RefreshScopeRefreshedEvent());
      }
    
    • GenericScope#destroy
      public void destroy() {
          ...
          Collection<BeanLifecycleWrapper> wrappers = <b>this.cache.clear()</b>;
          for (BeanLifecycleWrapper wrapper : wrappers) {
              <b>wrapper.destroy();</b>
          }
      }
    
  • Spring Cloud Bus 如何觸發(fā) Refresh

    • BusAutoConfiguration#BusRefreshConfiguration 發(fā)布一個(gè)RefreshBusEndpoint
    @Configuration
      @ConditionalOnClass({ Endpoint.class, RefreshScope.class })
      protected static class BusRefreshConfiguration {
    
          @Configuration
          @ConditionalOnBean(ContextRefresher.class)
          @ConditionalOnProperty(value = "endpoints.spring.cloud.bus.refresh.enabled", matchIfMissing = true)
          protected static class BusRefreshEndpointConfiguration {
              @Bean
              public RefreshBusEndpoint refreshBusEndpoint(ApplicationContext context,
                      BusProperties bus) {
                  return new RefreshBusEndpoint(context, bus.getId());
              }
          }
      }
    
    • RefreshBusEndpoint 會(huì)從http端口觸發(fā)廣播RefreshRemoteApplicationEvent事件
     @Endpoint(id = "bus-refresh")
      public class RefreshBusEndpoint extends AbstractBusEndpoint {
           public void busRefresh() {
              publish(new RefreshRemoteApplicationEvent(this, getInstanceId(), null));
          }
      }
    
    • BusAutoConfiguration#refreshListener 負(fù)責(zé)接收事件(所有配置bus的節(jié)點(diǎn))
      @Bean
      @ConditionalOnProperty(value = "spring.cloud.bus.refresh.enabled", matchIfMissing = true)
      @ConditionalOnBean(ContextRefresher.class)
      public RefreshListener refreshListener(ContextRefresher contextRefresher) {
          return new RefreshListener(contextRefresher);
      }
    
    • RefreshListener#onApplicationEvent 觸發(fā) ContextRefresher
    public void onApplicationEvent(RefreshRemoteApplicationEvent event) {
          Set<String> keys = contextRefresher.refresh();
      }
    
  • 大部分需要更新的服務(wù)需要打上@RefreshScope, EurekaClient是如何配置更新的

    • EurekaClientAutoConfiguration#RefreshableEurekaClientConfiguration
      @Configuration
      @ConditionalOnRefreshScope
      protected static class RefreshableEurekaClientConfiguration{
          @Bean
          @RefreshScope
          public EurekaClient eurekaClient(...) {
              return new CloudEurekaClient(manager, config, this.optionalArgs,
                      this.context);
          }
          
          @Bean
          @RefreshScope
          public ApplicationInfoManager eurekaApplicationInfoManager(...) {
              ...
              return new ApplicationInfoManager(config, instanceInfo);
          }
      }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,836評(píng)論 6 540
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,275評(píng)論 3 428
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,904評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,633評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,368評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,736評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,740評(píng)論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,919評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,481評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,235評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,427評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,968評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,656評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,055評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,348評(píng)論 1 294
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,160評(píng)論 3 398
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,380評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容