SpringCloud源码解析 -- Spring Cloud Config与@RefreshScope

本文通过阅读源码,分享Spring Cloud Config与@RefreshScope的实现原理。
源码分析基于Spring Cloud Hoxton

阅读本文之前,最好先了解Environment,PropertySources,可参考 -- SpringBoot源码解析 -- Logging,Environment启动

Config Server

我们都知道SpringCloud Config Server启动后,就可以通过url访问,获取配置内容。
既然这样,那Config Server中应该就有Controller,对,就是EnvironmentController。

EnvironmentController提供的HTTP接口返回的都是Environment,真正的配置内容保存在Environment#PropertySources中。
EnvironmentController通过EnvironmentRepository#findOne获取对应的Environment。
EnvironmentRepository是一个Environment仓库,可以从不同的配置中心获取配置内容,如JDBC、SVN、GIT等等。

EnvironmentController中使用的是EnvironmentEncryptorEnvironmentRepository,它会对Environment的内容加解密,EnvironmentEncryptorEnvironmentRepository#delegate是CompositeEnvironmentRepository,很明显,EnvironmentController的组合类,其中真正的处理类是MultipleJGitEnvironmentRepository,他可以管理多个git配置中心,实际通过JGitEnvironmentRepository获取某一个git配置中心上的配置内容。

JGitEnvironmentRepository#findOne -> AbstractScmEnvironmentRepository#findOne

public synchronized Environment findOne(String application, String profile,
        String label, boolean includeOrigin) {
    NativeEnvironmentRepository delegate = new NativeEnvironmentRepository(
            getEnvironment(), new NativeEnvironmentProperties());
    // #1
    Locations locations = getLocations(application, profile, label);    
    delegate.setSearchLocations(locations.getLocations());
    // #2
    Environment result = delegate.findOne(application, profile, "", includeOrigin); 
    result.setVersion(locations.getVersion());
    result.setLabel(label);
    return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(),
            getUri());
}

#1 由子类实现,getLocations会拉取配置中心的内容,保存为本地文件,并返回本地的路径
#2 通过NativeEnvironmentRepository生成Environment

JGitEnvironmentRepository#getLocations -> refresh

public String refresh(String label) {
    Git git = null;
    try {
        git = createGitClient();
        // #1
        if (shouldPull(git)) {
            FetchResult fetchStatus = fetch(git, label);
            if (this.deleteUntrackedBranches && fetchStatus != null) {
                deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
                        git);
            }
            checkout(git, label);
            tryMerge(git, label);
        }
        ...
        return git.getRepository().findRef("HEAD").getObjectId().getName();
    }
    ...
}

#1 refresh会判断是否需要fetch,并执行checkout,merge等操作

回到AbstractScmEnvironmentRepository#findOne方法#2步骤,看一下NativeEnvironmentRepository#findOne

public Environment findOne(String config, String profile, String label,
        boolean includeOrigin) {
    // #1
    SpringApplicationBuilder builder = new SpringApplicationBuilder(
            PropertyPlaceholderAutoConfiguration.class);    
    // #2
    ConfigurableEnvironment environment = getEnvironment(profile);
    builder.environment(environment);
    // #3
    builder.web(WebApplicationType.NONE).bannerMode(Mode.OFF);
    ...
    // #4
    String[] args = getArgs(config, profile, label);
    // #5
    builder.application()
            .setListeners(Arrays.asList(new ConfigFileApplicationListener()));
    // #6
    try (ConfigurableApplicationContext context = builder.run(args)) {
        environment.getPropertySources().remove("profiles");
        // #7
        return clean(new PassthruEnvironmentRepository(environment).findOne(config,
                profile, label, includeOrigin));
    }
    ...
}

#1 SpringApplicationBuilder使用SpringApplication#run构建一个ApplicationContext
#2 构造一个Environment,并赋值给SpringApplication#environment
#3 设置SpringApplication的WebApplicationType,定义构造的ApplicationContext的类型
#4 设置一些必要的参数,注意:前面保存的本地配置文件的路径会添加到--spring.config.location参数中,该参数会被下一步骤的ConfigFileApplicationListener使用
#5 ConfigFileApplicationListener会通过spring.config.location参数加载本地的配置文件,并添加到Environment#PropertySources中
#6 builder.run -> ApplicationContext#run,构造一个ApplicationContext,构造过程中ConfigFileApplicationListener会完成加载配置文件工作。
#7 清理Environment中一些非配置中心的PropertySources。
关于ApplicationContext#run,可参考SpringBoot启动过程

Spring Cloud Config client

来看一下其他应用如何使用Config Server的配置内容。
PropertySourceBootstrapConfiguration实现了ApplicationContextInitializer,
他会读取bootstrap.properties,bootstrap.yml等配置文件中Config Server的配置信息,并使用PropertySourceLocator获取Config Server的Environment,最后insertPropertySources将拉取到的PropertySources添加到本应用的Environment中。

ConfigServicePropertySourceLocator#locate方法通过RestTemplate获取Config Server的Environment,并将结果的PropertySource转化为对应的OriginTrackedMapPropertySource。

@RefreshScope

我们知道,如果要在运行时动态刷新配置值,需要在Bean上添加@RefreshScope,并使用spring-boot-starter-actuator提供的HTTP接口actuator/refresh来刷新配置值,现在来看看他们的实现原理。
Spring中,bean的范围有singleton,prototype以及不同的scope。
scope有RefreshScope,ThreadScope,SessionScope。
Spring中有@Scope注解和Scope接口以及对应的实现类,而@RefreshScope实际上就是一个scopeName为refresh的@Scope。

首先,读取@Scope注解,是在ClassPathBeanDefinitionScanner#doScan方法中,会通过AnnotationScopeMetadataResolver读取ScopeMetadata信息。
关于这部分内容,可参考 -- @ComponentScan的实现原理

scope的处理是在bean的构造过程中,AbstractBeanFactory#doGetBean

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
    @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    ...
    if (mbd.isSingleton()) {
        ...
        
    else if (mbd.isPrototype()) {
        ...
    else {
        String scopeName = mbd.getScope();
        // #1
        final Scope scope = this.scopes.get(scopeName);
        if (scope == null) {
            throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
        }
        try {
            Object scopedInstance = scope.get(beanName, () -> {
                beforePrototypeCreation(beanName);
                try {
                    return createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
            });
            bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
        }
        ...
    }   
    ...
}   

#1 Scope#get方法第二个参数是一个ObjectFactory,负责真正的构造Bean工作。而Scope#get方法主要针对不同的Scope做缓存操作。

Scope接口的基础实现在GenericScope中,而它的子类ThreadScope替换了ScopeCache,使用ThreadLocal保存Bean。另一个子类RefreshScope则提供了refreshAll等方法。

关于Bean的构造过程,可参考 -- bean构造原理

refresh
引入spring-boot-starter-actuator后,我们可以通过actuator/refresh来刷新@RefreshScope标注的类。
处理该请求的是RefreshEndpoint,调用链路 RefreshEndpoint#refresh -> ContextRefresher#refresh -> RefreshScope#refreshAll,该方法是之前的
ContextRefresher#refresh会刷新Environment的内容,并发布EnvironmentChangeEvent事件。
RefreshScope#refreshAll会销毁@RefreshScope标注的bean(还会发布RefreshScopeRefreshedEvent事件),这样先创建的bean就可以拿到最新的配置值了。

Spring Boot Actuator中Endpoint类似与SpringMvc的Controller,不过它可以通过HTTP和JMX暴露服务,以后有时间再说一下这部分内容。

如果您觉得本文不错,欢迎关注我的微信公众号,您的关注是我坚持的动力!


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269