本文通过阅读源码,分享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暴露服务,以后有时间再说一下这部分内容。

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


binecy
49 声望18 粉丝