溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

@RereshScope刷新的原理是什么

發(fā)布時(shí)間:2022-12-05 09:30:19 來源:億速云 閱讀:118 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“@RereshScope刷新的原理是什么”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“@RereshScope刷新的原理是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

    在配合配置中心修改配置讓應(yīng)用自動(dòng)刷新配置時(shí),我們要在需要感知配置變化的bean上面加上@RereshScope。如果我們不加上這注解,那么有可能無法完成配置自動(dòng)刷新。

    一、入口

    可以看到@RereshScope@Scope("refresh")(bean的作用域)的派生注解并指定了作用域?yàn)?code>refresh并在默認(rèn)情況下proxyMode= ScopedProxyMode.TARGET_CLASS使用CGLIB生成代理對(duì)象。

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Scope("refresh")
    @Documented
    public @interface RefreshScope {
        ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
    }

    ScopedProxyMode

    ScopedProxyMode表示作用域的代理模式,共有以下四個(gè)值:

    • DEFAULT:默認(rèn)no

    • NO:不使用代理

    • INTERFACES:使用JDK動(dòng)態(tài)代理

    • TARGET_CLASS:使用CGLIB動(dòng)態(tài)代理

    public enum ScopedProxyMode {
       /**
        * Default typically equals {@link #NO}, unless a different default
        * has been configured at the component-scan instruction level.
        */
       DEFAULT,
       /**
        * Do not create a scoped proxy.
        */
       NO,
       /**
        * Create a JDK dynamic proxy implementing <i>all</i> interfaces exposed by
        * the class of the target object.
        */
       INTERFACES,
       /**
        * Create a class-based proxy (uses CGLIB).
        */
       TARGET_CLASS;
    }

    二、配置類解析

    在上文刷新時(shí)會(huì)執(zhí)行BeanFacotryPostProcessor對(duì)beanDefinition修改和增加,其中配置類解析、類掃描的工作就是在其中執(zhí)行,而對(duì)于一個(gè)ScopedProxyMode.NO它會(huì)解析成一個(gè)ScopedProxyFactoryBean

    //ConfigurationClassBeanDefinitionReader配置類解析代碼片段
    definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    
    //如果需要生產(chǎn)代理則創(chuàng)建一個(gè)ScopedProxy的BeanDefinition
    static BeanDefinitionHolder applyScopedProxyMode(
    		ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
    
    	ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
    	if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
    		return definition;
    	}
    	boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
    	return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
    }
    
    //createScopedProxy 代碼片段 可以看到BeanDefinition是ScopedProxyFactoryBean
    RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);

    ScopedProxyFactoryBean-生成代理對(duì)象

    FactoryBean在注入時(shí)返回的是getObject()所返回的對(duì)象,在這里就是返回的就是proxy。ScopedProxyFactoryBean實(shí)現(xiàn)了BeanFactoryAware那么在這個(gè)bean初始化中會(huì)調(diào)用setBeanFactory()方法,而在這個(gè)方法中,為它創(chuàng)建一個(gè)CGLIB代理對(duì)象作為getObject()的返回值,并使用ScopedObject來代替被代理對(duì)象。而在ScopedObject默認(rèn)實(shí)現(xiàn)中每次都是從BeanFactory中獲?。ㄖ攸c(diǎn))。

    @Override
    public Object getObject() {
    	if (this.proxy == null) {
    		throw new FactoryBeanNotInitializedException();
    	}
        //返回代理對(duì)象
    	return this.proxy;
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
       //...省略其他代碼
        
       // Add an introduction that implements only the methods on ScopedObject.
       //增加一個(gè)攔截使用ScopedObject來被代理對(duì)象調(diào)用方法
       ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
       //委托ScopedObject去執(zhí)行
       pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));
    
       // Add the AopInfrastructureBean marker to indicate that the scoped proxy
       // itself is not subject to auto-proxying! Only its target bean is. AOP時(shí)復(fù)用這個(gè)代理對(duì)象
       pf.addInterface(AopInfrastructureBean.class);
       //創(chuàng)建代理對(duì)象   
       this.proxy = pf.getProxy(cbf.getBeanClassLoader());
    }

    ScopedObject-從容器中獲取代理目標(biāo)

    作用域?qū)ο蟮?code>AOP引入的接口??梢詫?code>ScopedProxyFactoryBean創(chuàng)建的對(duì)象強(qiáng)制轉(zhuǎn)換到此接口,從而可以控制訪問原始目標(biāo)對(duì)象并通過編程刪除目標(biāo)對(duì)象。在默認(rèn)實(shí)現(xiàn)中是每次方法攔截都從容器中獲取被代理的目標(biāo)對(duì)象。

    public interface ScopedObject extends RawTargetAccess {
      //返回當(dāng)前代理對(duì)象后面的目標(biāo)對(duì)象
       Object getTargetObject();
       void removeFromScope();
    }
    public class DefaultScopedObject implements ScopedObject, Serializable {
        //...省略字段信息和構(gòu)造器
    	@Override
    	public Object getTargetObject() {
            //從容器中獲取
    		return this.beanFactory.getBean(this.targetBeanName);
    	}
    	@Override
    	public void removeFromScope() {
    		this.beanFactory.destroyScopedBean(this.targetBeanName);
    	}
    }

    三、作用域原理

    BeanFactory獲取bean時(shí)(doGetBean),如果**不是單例或者原型bean**將交給對(duì)應(yīng)的Socpebean,而創(chuàng)建bean方式和單例bean是一樣的。其他作用域像request、session等等都是屬于這一塊的擴(kuò)展:SPI+策略模式

    //AbstractBeanFactory doGetBean()代碼片段
    String scopeName = mbd.getScope();
    //獲取對(duì)應(yīng)的scope
    final Scope scope = this.scopes.get(scopeName);
    //參數(shù)檢查省略。。。
    try {
        //使用的對(duì)應(yīng)的Socpe去獲取bean 獲取不到則使用后面的`ObjectFactory`
       Object scopedInstance = scope.get(beanName, () -> {    
           //ObjectFactory lambda表達(dá)式 怎么創(chuàng)建bean	
          beforePrototypeCreation(beanName);
          try {
             return createBean(beanName, mbd, args);
          }
          finally {
             afterPrototypeCreation(beanName);
          }
       });
       bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);

    RefreshScope繼承GenericScope每次獲取bean是從自己的緩存(ConcurrentHashMap)中獲取。 如果緩存中bean被銷毀了則用objectFactory創(chuàng)建一個(gè)。

    //GenericScope 中獲取get實(shí)現(xiàn)
    public Object get(String name, ObjectFactory<?> objectFactory) {
        //從緩存中獲取 緩存的實(shí)現(xiàn)就是ConcurrentHashMap
        BeanLifecycleWrapper value = this.cache.put(name, new BeanLifecycleWrapper(name, objectFactory));
        this.locks.putIfAbsent(name, new ReentrantReadWriteLock());
        try {
            return value.getBean();
        } catch (RuntimeException var5) {
            this.errors.put(name, var5);
            throw var5;
        }
    }
        private static class BeanLifecycleWrapper {
            //當(dāng)前bean對(duì)象
            private Object bean;
            //銷毀回調(diào)
            private Runnable callback;
            //bean名稱
            private final String name;
            //bean工廠
            private final ObjectFactory<?> objectFactory;
            //獲取
            public Object getBean() {
                if (this.bean == null) {
                    synchronized(this.name) {
                        if (this.bean == null) {
                            this.bean = this.objectFactory.getObject();
                        }
                    }
                }
                return this.bean;
            }
           //銷毀
            public void destroy() {
                if (this.callback != null) {
                    synchronized(this.name) {
                        Runnable callback = this.callback;
                        if (callback != null) {
                            callback.run();
                        }
                        this.callback = null;
                        //只為null
                        this.bean = null;
                    }
                }
            }
    }

    四、配置刷新

    當(dāng)配置中心刷新配置之后,有兩種方式可以動(dòng)態(tài)刷新Bean的配置變量值,(SpringCloud-Bus還是Nacos差不多都是這么實(shí)現(xiàn)的):

    • 向上下文發(fā)布一個(gè)RefreshEvent事件

    • Http訪問/refresh這個(gè)EndPoint

    不管是什么方式,最終都會(huì)調(diào)用ContextRefresher這個(gè)類的refresh方法

    public synchronized Set<String> refresh() {
         //刷新環(huán)境
         Set<String> keys = this.refreshEnvironment();
         //刷新bean 其實(shí)就是銷毀refreshScope中緩存的bean
         this.scope.refreshAll();
         return keys;
    }
    //RefreshScope刷新
    public void refreshAll() {
         super.destroy();
         this.context.publishEvent(new RefreshScopeRefreshedEvent());
    }

    讀到這里,這篇“@RereshScope刷新的原理是什么”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI