SpringCloud中动态配置刷新@RefreshScope的源码解析

@RefreshScope 动态刷新机制 一般在项目中,我们集成Nacos做统一配置管理,同时配置支持动态刷新,项目中都会用到@RefreshScope注解,这里和大家一起看看@RefreshScope实现动态刷新的原理。 阅读详情
@RefreshScope
public class App {
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
// 作用域为刷新作用域
@Scope("refresh")
@Documented
public @interface RefreshScope注解 {

    /**
     * 作用域代理的模式,默认为CGLIB
     */
    @AliasFor(annotation = Scope.class)
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}

// 导入刷新配置的核心处理类
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ConfigurationPropertiesBindingPostProcessor.class)
public class ConfigurationPropertiesRebinderAutoConfiguration implements ApplicationContextAware, SmartInitializingSingleton {
    // Spring上下文
    private ApplicationContext context;

    // 创建ConfigurationPropertiesBeans的Bean,它保存了所有标注在当前上下文中所有的ConfigurationProperties类
    @Bean
    @ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
    public static ConfigurationPropertiesBeans configurationPropertiesBeans() {
        return new ConfigurationPropertiesBeans();
    }

    // 注入将指定ConfigurationProperties类进行重新绑定
    @Bean
    @ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
    public ConfigurationPropertiesRebinder configurationPropertiesRebinder(ConfigurationPropertiesBeans beans) {
        ConfigurationPropertiesRebinder rebinder = new ConfigurationPropertiesRebinder(beans);
        return rebinder;
    }

    // 所有的Bena都初始化完成
    @Override
    public void afterSingletonsInstantiated() {
        // 如果存在父容器
        if (this.context.getParent() != null) {
            // 获取ConfigurationPropertiesRebinder该Bean
            ConfigurationPropertiesRebinder rebinder = this.context.getBean(ConfigurationPropertiesRebinder.class);
            // 获取父容器中所有的Bean进行重新加载
            for (String name : this.context.getParent().getBeanDefinitionNames()) {
                rebinder.rebind(name);
            }
        }
    }

}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RefreshScope.class)
@ConditionalOnProperty(name = RefreshAutoConfiguration.REFRESH_SCOPE_ENABLED, matchIfMissing = true)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
@EnableConfigurationProperties(RefreshAutoConfiguration.RefreshProperties.class)
public class RefreshAutoConfiguration {

    // 注册刷新作用域
    @Bean
    @ConditionalOnMissingBean(RefreshScope.class)
    public static RefreshScope refreshScope() {
        return new RefreshScope();
    }

    // 配置数据上下文的刷新器,它负责刷新该作用域下的所有bean
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBootstrapDisabled
    public ConfigDataContextRefresher configDataContextRefresher(ConfigurableApplicationContext context, RefreshScope scope, RefreshProperties properties) {
        return new ConfigDataContextRefresher(context, scope, properties);
    }

    /**
     * {@link com.alibaba.cloud.nacos.refresh.NacosContextRefresher#registerNacosListener(java.lang.String, java.lang.String)}
     * 配置刷新的监听器,该RefreshEvent是由对应的配置中心发布的事件,例如Nacos发生匹配变化的时候,就会触发一个RefreshEvent事件
     */
    @Bean
    public RefreshEventListener refreshEventListener(ContextRefresher contextRefresher) {
        return new RefreshEventListener(contextRefresher);
    }
}

// 配置数据上下文的刷新器,它负责刷新该作用域下的所有bean
public class ConfigDataContextRefresher extends ContextRefresher implements ApplicationListener<ContextRefreshedWithApplicationEvent> {
    // Spring上下文对象
    private ConfigurableApplicationContext context;
    // 刷新作用域的实现
    private RefreshScope scope;
    // SpringBoot的配置为了
    private SpringApplication application;

    @Override
    public void onApplicationEvent(ContextRefreshedWithApplicationEvent event) {
        application = event.getSpringApplication();
    }

    // 更新环境对象,返回一个新的环境对象
    @Override
    protected void updateEnvironment() {
        // 拷贝一份上下文环境存在的属性对象
        StandardEnvironment environment = copyEnvironment(getContext().getEnvironment());
        ConfigurableBootstrapContext bootstrapContext = getContext().getBeanProvider(ConfigurableBootstrapContext.class).getIfAvailable(DefaultBootstrapContext::new);
        // 加载所有的EnvironmentPostProcessor后置处理器
        List<String> classNames = SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, getClass().getClassLoader());

        Instantiator<EnvironmentPostProcessor> instantiator = new Instantiator<>(EnvironmentPostProcessor.class,
                (parameters) -> {
                    parameters.add(DeferredLogFactory.class, logFactory);
                    parameters.add(Log.class, logFactory::getLog);
                    parameters.add(ConfigurableBootstrapContext.class, bootstrapContext);
                    parameters.add(BootstrapContext.class, bootstrapContext);
                    parameters.add(BootstrapRegistry.class, bootstrapContext);
                });
        // 实例化所有EnvironmentPostProcessor的类
        List<EnvironmentPostProcessor> postProcessors = instantiator.instantiate(classNames);
        for (EnvironmentPostProcessor postProcessor : postProcessors) {
            // 对拷贝的环境对象进行后置处理操作
            postProcessor.postProcessEnvironment(environment, application);
        }
        // 如果包含refreshArgs属性,将该属性移除
        if (environment.getPropertySources().contains(REFRESH_ARGS_PROPERTY_SOURCE)) {
            environment.getPropertySources().remove(REFRESH_ARGS_PROPERTY_SOURCE);
        }
        // 获取环境对象中的所有属性
        MutablePropertySources target = getContext().getEnvironment().getPropertySources();
        String targetName = null;
        // 保持属性的顺序
        for (PropertySource<?> source : environment.getPropertySources()) {
            String name = source.getName();
            if (target.contains(name)) {
                targetName = name;
            }
            if (!this.standardSources.contains(name)) {
                if (target.contains(name)) {
                    target.replace(name, source);
                } else {
                    if (targetName != null) {
                        target.addAfter(targetName, source);
                        targetName = name;
                    } else {
                        target.addFirst(source);
                        targetName = name;
                    }
                }
            }
        }
    }

    // 刷新配置以及对应的配置为了
    public synchronized Set<String> refresh() {
        // 刷新环境对象
        Set<String> keys = this.refreshEnvironment();
        // 刷新标注了@RefreshScope的类
        this.scope.refreshAll();
        return keys;
    }

    // 刷新环境对象,返回发生变化的属性
    public synchronized Set<String> refreshEnvironment() {
        Map<String, Object> before = extract(this.context.getEnvironment().getPropertySources());
        // 更新环境对象,返回一个新的环境对象
        this.updateEnvironment();
        // 获取发生变化的属性名
        Set<String> keys = this.changes(before, extract(this.context.getEnvironment().getPropertySources())).keySet();
        /**发布一个事件,该事件会由{@link ConfigurationPropertiesRebinder#onApplicationEvent(EnvironmentChangeEvent)}处理,从而刷新标注了**/
        this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys));
        // 返回发生变化的属性
        return keys;
    }

    // 将原始的属性与当前的属性做对比,提取出发生变化的属性
    private Map<String, Object> changes(Map<String, Object> before, Map<String, Object> after) {
        Map<String, Object> result = new HashMap<>();
        for (String key : before.keySet()) {
            if (!after.containsKey(key)) {
                result.put(key, null);
            } else if (!equal(before.get(key), after.get(key))) {
                result.put(key, after.get(key));
            }
        }
        for (String key : after.keySet()) {
            if (!before.containsKey(key)) {
                result.put(key, after.get(key));
            }
        }
        return result;
    }
}

@ManagedResource
public class RefreshScope extends GenericScope implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, Ordered {
    // 刷新当前作用域的所有Bean
    public void refreshAll() {
        /**
         * 创建该作用域Bean的流程{@link RefreshScope#get(String, ObjectFactory)}
         */
        // 销毁所有refresh作用域的@Bean,下次需要发现该作用域没有缓存该Bean,则又会触发Bean的创建
        super.destroy();
        // 发布作用域刷新事件,这个事件我们自己可以监听的做一些事情
        this.context.publishEvent(new RefreshScopeRefreshedEvent());
    }

    /**
     * <pre>
     *     获取Bean对象,如果Bean对象不存在,则创建Bean
     *    // 根据不同的作用域来创建对象
     *    if (mbd.isSingleton()) {
     *        // 从单例池中获取,不存在则创建
     *        sharedInstance = getSingleton(beanName, () -> {
     * 	    	return createBean(beanName, mbd, args);
     *        });
     * 	    beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
     *    }
     *    else if (mbd.isPrototype()) {
     *       // 直接创建
     *       prototypeInstance = createBean(beanName, mbd, args);
     *       beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
     *    }
     *    // 其他作用域
     *    else {
     *        // 获取自定义作用域的Scope对象
     *        String scopeName = mbd.getScope();
     * 		  Scope scope = this.scopes.get(scopeName);
     * 		  // 调用Scope的get方法,从该作用域中获取Bean对象,如果不存在则创建对象
     *          {@link BeanLifecycleWrapper#get(String, ObjectFactory)}
     * 		  Object scopedInstance = scope.get(beanName, () -> {
     * 		  		return createBean(beanName, mbd, args);
     *          });
     * 		  beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
     *    }
     * </pre>
     */
    // 自定义作用域的get方法,从指定位置返回该作用域的Bean对象,这个Bean对象由自己管理
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        // 缓存当前Bean
        BeanLifecycleWrapper value = this.cache.put(name, new BeanLifecycleWrapper(name, objectFactory));
        // 加读写锁
        this.locks.putIfAbsent(name, new ReentrantReadWriteLock());
        try {
            return value.getBean();
        } catch (RuntimeException e) {
            this.errors.put(name, e);
            throw e;
        }
    }
}

// Bean的Scope生命周期包装类
public class BeanLifecycleWrapper {

    // BeanName
    private final String name;
    // 创建Bean的工厂
    private final ObjectFactory<?> objectFactory;
    // Bean对象
    private volatile Object bean;
    // 销毁Bean执行的任务
    /**
     * 在创建的Bean的时候,如果Bean是DisposableBean类型,会自动注册一个任务,就是将该Bean执行所有的DestructionAwareBeanPostProcessor,处理一些销毁逻辑
     * {@link AbstractBeanFactory#registerDisposableBeanIfNecessary(String, Object, RootBeanDefinition)}
     */
    private Runnable callback;

    BeanLifecycleWrapper(String name, ObjectFactory<?> objectFactory) {
        this.name = name;
        this.objectFactory = objectFactory;
    }

    public String getName() {
        return this.name;
    }

    public void setDestroyCallback(Runnable callback) {
        this.callback = callback;
    }

    // 获取Bean对象
    public Object getBean() {
        // 是否存在Bean对象
        if (this.bean == null) {
            synchronized (this.name) {
                // 使用对象工厂创建Bean对象
                if (this.bean == null) {
                    // 保存Bean对象
                    this.bean = this.objectFactory.getObject();
                }
            }
        }
        return this.bean;
    }

    // 销毁Bean对象
    public void destroy() {
        // 如果没有设置销毁时需要执行的任务,则不处理任何东西
        if (this.callback == null) {
            return;
        }
        synchronized (this.name) {
            // 执行指定的销毁任务
            Runnable callback = this.callback;
            if (callback != null) {
                callback.run();
            }
            // 清空当前Bean对象
            this.callback = null;
            this.bean = null;
        }
    }
}

public class GenericScope implements Scope, BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor, DisposableBean {
    // 所有继承该类的作用域保存对应Bean的缓存对象
    private BeanLifecycleWrapperCache cache = new BeanLifecycleWrapperCache(new StandardScopeCache());

    // 销毁对象
    @Override
    public void destroy() {
        // 清空所有该作用域的缓存Bean
        Collection<BeanLifecycleWrapper> wrappers = this.cache.clear();
        // 遍历所有该作用域的Bean的包装对象
        for (BeanLifecycleWrapper wrapper : wrappers) {
            // 调用每一个Bean包装器的销毁方法
            wrapper.destroy();
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
        // 注册当前作用域为refresh
        beanFactory.registerScope(this.name, this);
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 获取所有的Bean
        for (String name : registry.getBeanDefinitionNames()) {
            BeanDefinition definition = registry.getBeanDefinition(name);
            if (definition instanceof RootBeanDefinition root) {
                // 如果是作用域代理的Bean
                if (root.getDecoratedDefinition() != null && root.hasBeanClass() && root.getBeanClass() == ScopedProxyFactoryBean.class) {
                    // 并且当前Bean的作用域正好是refresh
                    if (getName().equals(root.getDecoratedDefinition().getBeanDefinition().getScope())) {
                        // 修改当前Bean的BeanClass,增强一下,从ScopedProxyFactoryBean变成LockedScopedProxyFactoryBean
                        // 它是继承ScopedProxyFactoryBean,就是在执行的过程中添加了读写锁
                        root.setBeanClass(LockedScopedProxyFactoryBean.class);
                        // 添加构造参数
                        root.getConstructorArgumentValues().addGenericArgumentValue(this);
                        root.setSynthetic(true);
                    }
                }
            }
        }
    }
}


/**
 * {@link com.alibaba.cloud.nacos.refresh.NacosContextRefresher#registerNacosListener(java.lang.String, java.lang.String)}
 * 配置刷新的监听器,该RefreshEvent是由对应的配置中心发布的事件,例如Nacos发生匹配变化的时候,就会触发一个RefreshEvent事件
 */
public class RefreshEventListener implements SmartApplicationListener {
    // 配置数据上下文的刷新器
    private ConfigDataContextRefresher refresh;
    // 配置是否就绪
    private AtomicBoolean ready = new AtomicBoolean(false);

    public RefreshEventListener(ContextRefresher refresh) {
        this.refresh = refresh;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationReadyEvent.class.isAssignableFrom(eventType) || RefreshEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            // 标记已就绪
            this.ready.compareAndSet(false, true);
        }
        if (event instanceof RefreshEvent) {
            // 已就绪才会处理
            if (this.ready.get()) {
                // 使用配置数据的上下文对象进行刷新
                Set<String> keys = this.refresh.refresh();
            }
        }
    }
}

@Component
public class ConfigurationPropertiesBeans implements BeanPostProcessor, ApplicationContextAware {
    // 标注了ConfigurationProperties的Bean对象
    private Map<String, ConfigurationPropertiesBean> beans = new HashMap<>();
    // Spring上下文
    private ApplicationContext applicationContext;
    // Bean工厂
    private ConfigurableListableBeanFactory beanFactory;
    // 刷新作用域
    private String refreshScope;
    // 刷新作用域是否初始化了
    private boolean refreshScopeInitialized;
    // 父容器中的ConfigurationPropertiesBeans
    private ConfigurationPropertiesBeans parent;

    // 初始化当前上下文中父容器的配置类ConfigurationProperties的Bean对象
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        if (applicationContext.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
            this.beanFactory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        }
        AutowireCapableBeanFactory bf = applicationContext.getParent().getAutowireCapableBeanFactory();
        // 如果存在父容器
        if (applicationContext.getParent() != null && bf instanceof ConfigurableListableBeanFactory listable) {
            // 从父容器中获取获取ConfigurationPropertiesBeans
            String[] names = listable.getBeanNamesForType(ConfigurationPropertiesBeans.class);
            // 如果只存在一个
            if (names.length == 1) {
                // 将该父容器中的ConfigurationPropertiesBeans保存
                this.parent = (ConfigurationPropertiesBeans) listable.getBean(names[0]);
                // 将父容器中的ConfigurationProperties的Bean对象保存
                this.beans.putAll(this.parent.beans);
            }
        }
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 判断容器中的bean是不是refresh作用域
        // 如果是,不处理
        if (this.isRefreshScoped(beanName)) {
            return bean;
        }
        // 如果不是refresh作用域,获取执行beanName的Bean对象,标注了ConfigurationProperties才会返回对象
        // 如果不存在ConfigurationProperties注解,返回null
        ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName);
        // 如果是属性配置Bean
        if (propertiesBean != null) {
            // 保存当前配置Bean信息
            this.beans.put(beanName, propertiesBean);
        }
        return bean;
    }

    // 判断容器中的bean是不是refresh作用域
    private boolean isRefreshScoped(String beanName) {
        // 如果刷新作用域为空(默认)并且没有被初始化过
        if (this.refreshScope == null && !this.refreshScopeInitialized) {
            // 开始初始化,标记初始化
            this.refreshScopeInitialized = true;
            // 遍历当前容器中的保存的所有作用域(例如,单例,原型,会话等等
            for (String scope : this.beanFactory.getRegisteredScopeNames()) {
                // 从容器中获取RefreshScope的Bean对象,如果当前作用域是RefreshScope,则保存该作用域
                if (this.beanFactory.getRegisteredScope(scope) instanceof org.springframework.cloud.context.scope.refresh.RefreshScope) {
                    this.refreshScope = scope;
                    break;
                }
            }
        }
        // 如果beanName为空或者没找到RefreshScope的Bean,表示不是RefreshScope
        if (beanName == null || this.refreshScope == null) {
            return false;
        }
        // 如果当前Bean工厂包含指定的Bean,并且该Bean的作用域正是refresh(该Bean标注了@RefreshScope),返回true
        return this.beanFactory.containsBeanDefinition(beanName) && this.refreshScope.equals(this.beanFactory.getBeanDefinition(beanName).getScope());
    }

    // 获取所有标注了ConfigurationProperties的Bean对象的BeanName
    public Set<String> getBeanNames() {
        return new HashSet<>(this.beans.keySet());
    }

}

// 配置属性Bean的重新绑定器
@Component
@ManagedResource
public class ConfigurationPropertiesRebinder implements ApplicationContextAware, ApplicationListener<EnvironmentChangeEvent> {
    // 需要重新绑定的配置类
    private ConfigurationPropertiesBeans beans;
    // Spring上下文对象
    private ApplicationContext applicationContext;
    // 重新绑定过程中的异常
    private Map<String, Exception> errors = new ConcurrentHashMap<>();

    // 需要将哪些配置Bean进行重新绑定
    public ConfigurationPropertiesRebinder(ConfigurationPropertiesBeans beans) {
        this.beans = beans;
    }

    // 重新绑定所有配置类
    @ManagedOperation
    public void rebind() {
        // 清空所有的异常信息
        this.errors.clear();
        // 遍历当前需要重新绑定的配置类Bean名称
        for (String name : this.beans.getBeanNames()) {
            // 重新绑定
            this.rebind(name);
        }
    }

    // 重新绑定指定配置类
    @ManagedOperation
    public boolean rebind(String name) {
        // 如果当前名称不在需要重新绑定的名单中,不处理
        if (!this.beans.getBeanNames().contains(name)) {
            return false;
        }
        ApplicationContext appContext = this.applicationContext;
        // 遍历所有层级的Spring上下文
        while (appContext != null) {
            // 如果包含该配置Bean,进行重新绑定
            if (appContext.containsLocalBean(name)) {
                return rebind(name, appContext);
            }
            // 如果当前容器不包含当前配置Bean,则查找父容器
            else {
                appContext = appContext.getParent();
            }
        }
        return false;
    }

    // 根据指定类型绑定
    public boolean rebind(Class type) {
        // 获取指定类型的配置Bean
        String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, type);
        if (beanNamesForType.length > 0) {
            // 获取到该Bean最原始的BeanName,因为该Bean可能设置了作用域代理
            String name = beanNamesForType[0];
            // 如果是作用域代理的Bean
            if (ScopedProxyUtils.isScopedTarget(name)) {
                // 获取最原始的bean名称,因为作用域代理的beanName经过加工
                name = ScopedProxyUtils.getOriginalBeanName(name);
            }
            // 开始绑定
            return rebind(name, this.applicationContext);
        }
        return false;
    }

    // 真正的开始查询绑定
    private boolean rebind(String name, ApplicationContext appContext) {
        try {
            // 获取需要绑定的Bean
            Object bean = appContext.getBean(name);
            // 获取到原始对象
            if (AopUtils.isAopProxy(bean)) {
                bean = ProxyUtils.getTargetObject(bean);
            }
            if (bean != null) {
                // 如果设置了不支持刷新,不处理
                if (getNeverRefreshable().contains(bean.getClass().getName())) {
                    return false;
                }
                // 销毁该Bean
                appContext.getAutowireCapableBeanFactory().destroyBean(bean);
                // 重新初始化该Bean
                appContext.getAutowireCapableBeanFactory().initializeBean(bean, name);
                return true;
            }
        } catch (RuntimeException e) {
            // 保存绑定的异常信息
            this.errors.put(name, e);
            throw e;
        } catch (Exception e) {
            this.errors.put(name, e);
            throw new IllegalStateException("Cannot rebind to " + name, e);
        }
        return false;
    }

    // 不支持刷新
    @ManagedAttribute
    public Set<String> getNeverRefreshable() {
        String neverRefresh = this.applicationContext.getEnvironment().getProperty("spring.cloud.refresh.never-refreshable", "com.zaxxer.hikari.HikariDataSource");
        return StringUtils.commaDelimitedListToSet(neverRefresh);
    }

    @ManagedAttribute
    public Set<String> getBeanNames() {
        return new HashSet<>(this.beans.getBeanNames());
    }

    // 如何监听到环境对象发生了改变,需要重新绑定
    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        // 在配置属性发生改变的时候,会发布这个事件
        /**
         * {@link ConfigDataContextRefresher#refreshEnvironment}
         */
        if (this.applicationContext.equals(event.getSource()) || event.getKeys().equals(event.getSource())) {
            this.rebind();
        }
    }

}

SpringCloud 配置动态刷新 @RefreshScope 注解 1.SpringCloud程序的存在一个自动装配的类,这个类默认情况下会自动初始化一个实例,该实例是的子类,然后注册到容器中。(,)2.当容器启动的时候,会自己把自己注册到scope中()()3.然后当自定义的Bean(被修饰)注册的时候,会被容器读取到其作用域为refresh。()通过上面三步,一个带有的自定义Bean就被注册到容器中来,其作用域为refresh。4.当我们后续进行以来查找的时候,会绕过Singleton和Prototype分支,进入最后一个分支,通过调用Scope接口的。 阅读详情

相关推荐

@RefreshScope源码解析

RefeshScope这个注解想必大家都用过,在微服务配置中心的场景下经常出现,它可以用来刷新Bean中的属性配置,那么它是如何做到的呢?让我们来一步步揭开它神秘的面纱。就是说我们在修改了bean属性的时候项目不需要重新启动,就可以拿到最新的值。我们先来看下@RefreshScope的接口@Target({/***/ //创建基于类的代理(使用 CGLIB) ScopedProxyMode proxyMode() default ScopedProxyMode . TARGET_CLASS;

BushRo 2863

一文带你理解@RefreshScope注解实现动态刷新原理

RefeshScope这个注解想必大家都用过,在微服务配置中心的场景下经常出现,他可以用来刷新Bean中的属性配置,那大家对他的实现原理了解吗?它为什么可以做到动态刷新呢?上面是这个RefreshScope实现动态刷新大致的原理,其中里面还有很多细节,可能需要留给大家自己debug去深入理解。...

m0_71777195的博客 3万+

Nacos+@RefreshScope 为什么配置能动态刷新?

上面是这个RefreshScope实现动态刷新大致的原理,其中里面还有很多细节,可能需要留给大家自己debug去深入理解。

m0_71777195的博客 432

SpringCloud配置动态刷新@RefreshScope注解

spring cloud config或sprring cloud alibaba nacos作为配置中心,其实现原理就是通过@RefreshScope 来实现对象属性的的动态更新。 实现@RefreshScope 动态刷新的就需要以下几个: @ Scope注解 @RefreshScope注解 RefreshScope类 GenericScope类 Scope接口 ContextRefresher @RefreshScope 能实现动态刷新全仰仗着@Scope 这个注解。 一、@Scope注解 @Tar

骑个小蜗牛的博客 4万+

数学建模入门——数据预处理(全)

介绍了数据预处理的入门知识

n04j04h06的博客 4354

ArcGIS中如何计算多个点到特定线的最短距离

现有一个点图层和一个面图层,怎么来计算这些点到这个面图层,两个面的公共边的最短直线距离呢? 1.首先得将两个图层都转为 投影坐标系 打开工具箱-数据管理工具-要素-面转线 ​ ​ 2.将面图层设为输入要素 注意要将“识别和存储面邻域信息”勾选 ​ 3.面转线成功后 打开线属性表,线图层拥有了 LEFT_FID和RIGHT_FID两个字段 ​ 4.按属性选择,表达式中输入 “LEFT_FID”<>-1 即可选出两个面的公共边 ​再将选...

GIS蒲公英的博客 6730

【Nacos】@NacosValue的使用与原理

在SpringCloud工程中,可以使用@RefreshScope+@Value实现配置文件内容变更后的动态刷新。在SpringBoot工程中,可以使用@NacosValue来实现配置文件内容变更后的动态刷新。

morris 2万+

【毕业设计】QT实战:从零构建仿QQ通讯系统,打造你的简历亮点项目

本文为计算机专业毕业生提供了一份详尽的毕业设计实战指南,教你如何从零开始使用QT框架构建一个仿QQ的即时通讯系统。文章深入剖析了项目规划、核心模块(登录、聊天、好友管理)的实现、TCP粘包处理、数据库设计等关键技术难点,并分享了如何将此项目打造成简历亮点,有效提升求职竞争力。

omega的博客 446

Nacos笔记——配置中心与服务注册发现

Nacos Nacos是阿里云提供的一个配置中心与服务注册发现中心组件。官网:https://nacos.io/zh-cn/docs/what-is-nacos.html 相关注解 @RefreshScope @EnableDiscoveryClient @LoadBalance SpringCloud结合Nacos的示例在官网中已经很清楚了,在这里我就只记录一下我自己在SpringCloud中使用Nacos遇到的问题和解答。 1. @RefreshScope是如何工作? 总结:RefreshScope其实

weixin_42440637的博客 435

开源低场MRI系统构建:从原理到三天实现

磁共振成像(MRI)作为现代医学影像的核心技术,其高场强系统存在成本和技术门槛问题。低场MRI通过开源硬件和模块化设计实现技术民主化,采用永磁体替代超导磁体可大幅降低系统复杂度。本文以H型永磁体设计为例,结合MaRCoS开源控制库和PyPulseq脉冲序列工具,展示了如何快速构建教育级MRI系统。关键技术包括遗传算法优化的匀场方案、CNC加工的梯度线圈,以及基于Red Pitaya的SDR控制架构。这种轻量化方案特别适合医学物理教学和脉冲序列开发验证,为MRI技术在资源有限地区的普及提供了新思路。

weixin_30470643的博客 458

Python深度学习基于Tensorflow(17)基于Transformer的图像处理实例VIT和Swin-T

定义窗口注意力机制,与普通的注意力机制不同,其是在各个窗口中执行注意力机制。从中可以看到,其创新点主要是将图片进行拆分作为序列数据带入。差不多,主要实现的是一个下采样的算法过程;相同位置的像素绑定到一起构成一张新的。模型定义完毕后,初始化模型并开始训练。由于层之间重复性出现,可以定义一个。中,这里先实现拆分图片类。进行操作时我们定义三个类。定义一个多头注意力机制类。的数据,导入数据如下。导入数据,这里同样用。

bigcrab的博客 1639

Spring Cloud中@RefreshScope实现动态刷新的原理

在现代微服务架构中,Spring Cloud已经成为了一种流行的选择,它提供了许多用于构建和部署微服务的工具和库。其中,动态刷新配置是Spring Cloud中一个非常有用的特性,它允许我们在不重启服务的情况下更新配置。这个特性是通过@RefreshScope注解来实现的。在本文中,我们将深入探讨@RefreshScope在Spring Cloud中是如何工作的。

码到三十五 3153

怎么调用onenet平台的API从而读取我们的设备数据和下发命令,做到控制开关

怎么调用onenet平台的API从而读取我们的设备数据和下发命令,做到控制开关 1、首先是怎么读取数据 读取的API是:http://api.heclouds.com/devices/datapoints?devIds=629063002 其中devids这个指的是你的设备ID 然后在我们的headers里面添加一些必要参数,就可以调用了 其中api-key的是你产品里面的master-apikey 把我们的参数写好就可以调用了,选择get方式,点击发送 这个value就是我们需要获取到的参数值了,

zyh960的博客 2万+

Springcloud中的@RefreshScope详解

3.当应用首次请求一个被@RefreshScope标记的Bean时,Spring容器会调用RefreshScope的get方法来创建Bean的实例,创建完成后,这个Bean实例会被缓存在RefreshScope中,以便后续快速获取。@RefreshScope注解是Spring Cloud中的一个注解,它用来实现Bean中属性的动态刷新,这意味着您可以在不停止和重新启动应用程序的情况下更改配置,它在微服务配置中心的场景下经常出现。8.经过刷新操作后,应用中的Bean将使用新的配置。

qq_42077317的博客 3999

DMC-E 系列总线控制卡----雷赛板卡介绍(十七)

低的速度平稳地接近目标位置,降低运动部件对接触点的冲击。设置插补目标位置,插补方向,以确定插补动作。圆形区域限位,即运动仅在用户设定的圆形范围内进行,超出这个范围,运动会依据设定。首先,用户需要绑定两个轴进而确定该功能所处的坐标系。仅支持平面圆形限位,不支持空间圆形限位。径,可以确定该区域在坐标系中的位置。)运动开始前,用户应当将旋转轴调整到与插补曲线的起点位置相切的角度;可以配合椭圆插补或圆弧插补运动,实现跟随轴的旋转运动角度与曲线当前。外,其它运动形式若开始运动时在限位区域外,则禁止运动;

A_nanda的博客 659

镜头像差之五——场曲

什么是场曲? 场曲[curvature of field] 物面上所有的点经过系统后,最佳焦点位置不在同一平面上,若这些像点所成的面为曲面,则称为系统有场曲。 与物高二次方、入射光瞳口径一次方成正比的像差。若仅存在场曲,则所有物平面上的点都有相应的像点,但分布在一个球面上;若采用弯成此种形状的底片,则可获得处处清晰的像。此时在理想像平面上,像点呈现为圆斑。 第一张图是最简单也是最容易理解的场曲,也就是对焦点锐利,其余部分逐渐松散,但实际上大多现代镜头的场曲都呈现为图二的形态:对焦点与边缘锐度.

camerall 1万+

【手把手教你搭建SpringCloud 08】动态配置更新:基于@RefreshScope实现配置热刷新

Spring Cloud动态配置更新摘要 本文深入讲解了Spring Cloud Alibaba中基于@RefreshScope实现配置热刷新的机制。主要内容包括: 动态配置更新的必要性:微服务架构中需要避免重启应用来实现配置变更,确保高可用性和业务连续性。 @RefreshScope核心机制: 通过代理模式实现Bean的动态刷新 配合@Value注解使用实现配置动态更新 利用缓存机制和事件发布实现Bean实例的销毁与重建 最佳实践: 展示了完整的配置示例和复杂业务场景下的使用方式 通过Nacos配置中心实

专注后端技术架构,AI技术分享 1476

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

@refreshscope 注解_SpringCloud源码解析 Spring Cloud Config与@RefreshScope

本文通过阅读源码,分享Spring Cloud Config与@RefreshScope的实现原理。源码分析基于Spring Cloud Hoxton(源码解析类文章建议在PC端阅读)阅读本文之前,最好先了解Environment,PropertySources,可参考 -- SpringBoot源码解析 -- Logging,Environment启动Config Server我们都知...

weixin_39872257的博客 511

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

@RefreshScope注解底层源码分析

最近在研究Spring Cloud和Spring Cloud Alibaba源码,在看到Nacos的配置中心的时候,有注意到自动刷新配置的玩法,底层实现依靠@RefreshScope注解。那么为什么要写这篇文章呢?笔者认为@RefreshScope注解源码实现跨度特别大,从Spring Cloud Alibaba 到Spring Cloud 到 Spring Boot 再到Spring,笔者认为能够理解它的源码实现的话对Spring全家桶的理解又能上升一个档次~版本如果下: 先会用,再深入源码,所以我们

李哈zzz的博客 1476

从源码的角度解读 Nacos 是如何动态刷新配置的

是 Spring Cloud 提供的注解,主要用于 ​支持配置的动态刷新​,特别是在结合像 Nacos、Consul、Spring Cloud Config 等配置中心时使用。使得标注的 Bean 在配置变更并发布刷新事件时,能够被重新实例化,从而实现“​配置热更新​”。触发流程内部有线程定时轮询配置变化;当检测到配置变更后,会回调配置监听器;是 Spring Cloud Alibaba 提供的监听器;它触发事件;Spring Cloud Context 的监听;

weixin_42353706的博客 430

SpringCloud-分布式配置中心【动态刷新】

给大家送一个小福利附高清脑图,高清知识点讲解教程,以及一些面试真题及答案解析。送给需要的提升技术、准备面试跳槽、自身职业规划迷茫的朋友们。《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!给大家送一个小福利[外链图片转存中…(img-HiXZY1EY-1713327671546)]附高清脑图,高清知识点讲解教程,以及一些面试真题及答案解析。送给需要的提升技术、准备面试跳槽、自身职业规划迷茫的朋友们。

2401_83916355的博客 850
上一篇: SpringCloud中@EnableDiscoveryClient的源码解析
下一篇: SpringCloud中@EnableFeignClients和FeignClient的源码解析
安缇吖
博客等级 码龄9年 411粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址