Spring远程加载配置的实现方法详解

前要

本文以携程的Apollo和阿里的Nacos为例。

pom中引入一下依赖:

  1.          <dependency>
  2.              <groupId>com.ctrip.framework.apollo</groupId>
  3.              <artifactId>apollo-client</artifactId>
  4.              <version>2.0.1</version>
  5.          </dependency>
  6.          <dependency>
  7.              <groupId>com.alibaba.cloud</groupId>
  8.              <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
  9.              <version>2021.1</version>
  10.          </dependency>

不管是Apollo还是Nacos,实现从远程加载配置都是通过ConfigurableEnvironmentPropertySource完成的,步骤如下:

  • 远程拉取配置,生成PropertySource
  • ConfigurableEnvironment获取聚合类 MutablePropertySources propertySources = ConfigurableEnvironment#getPropertySources();
  • 将拉取的PropertySource添加到从ConfigurableEnvironment获取的聚合类MutablePropertySources#add...(PropertySource<?> propertySource)

至于这个过程是怎么触发和运行的,要看具体实现。

  • 在apollo-client中,使用BeanFactoryPostProcessor。
  • 在spring-cloud-starter-alibaba-nacos-config中,由于 cloud-nacos实现了spring cloud config规范(处于org.springframework.cloud.bootstrap.config包下),nacos实现该规范即可,即实现spring cloud 的PropertySourceLocator接口。

Apollo

关注PropertySourcesProcessor ,该类为一个BeanFactoryPostProcessor,同时为了获取ConfigurableEnvironment,该类实现了EnvironmentAware回调接口。该类何时被加入spring容器?是通过@EnableApolloConfig@Import注解的类ApolloConfigRegistrar来加入,常规套路。

  1. public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware,
  2.      ApplicationEventPublisherAware, PriorityOrdered {
  3.      // aware回调接口设置
  4.      private ConfigurableEnvironment environment;
  5.      @Override
  6.      public void setEnvironment(Environment environment) {
  7.      //it is safe enough to cast as all known environment is derived from ConfigurableEnvironment
  8.      this.environment = (ConfigurableEnvironment) environment;
  9.      }
  10.      @Override
  11.      public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  12.      // 获取配置
  13.      this.configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  14.      // 从远程获取PropertySource
  15.      initializePropertySources();
  16.      // 为每个ConfigPropertySource注册ConfigChangeEvent监听器
  17.      // 监听器监听到ConfigChangeEvent后publish一个ApolloConfigChangeEvent
  18.      // 等于将apollo自定义的ConfigChangeEvent事件机制转化为了spring的ApolloConfigChangeEvent事件
  19.      initializeAutoUpdatePropertiesFeature(beanFactory);
  20.      }
  21.      private void initializePropertySources() {
  22.          // 聚合类,该类也是一个PropertySource,代理了一堆PropertySource
  23.          // 该类中有一个 Set<PropertySource<?>> 字段
  24.          CompositePropertySource composite = new …;
  25.          
  26.          // 从 远程 或 本地缓存 获取配置
  27.          Config config = ConfigService.getConfig(namespace);
  28.          // 适配Config到PropertySource,并加入聚合类
  29.          composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
  30.          // 添加到ConfigurableEnvironment
  31.          environment.getPropertySources().addFirst(composite);
  32.      }
  33.      private void initializeAutoUpdatePropertiesFeature(ConfigurableListableBeanFactory beanFactory) {
  34.      if (!AUTO_UPDATE_INITIALIZED_BEAN_FACTORIES.add(beanFactory)) {
  35.          return;
  36.      }
  37.          // 定义监听器,监听器监听到ConfigChangeEvent后发布ApolloConfigChangeEvent
  38.      ConfigChangeListener configChangeEventPublisher = changeEvent ->
  39.          applicationEventPublisher.publishEvent(new ApolloConfigChangeEvent(changeEvent));
  40.          // 注册监听器到每个PropertySource
  41.      List<ConfigPropertySource> configPropertySources = configPropertySourceFactory.getAllConfigPropertySources();
  42.      for (ConfigPropertySource configPropertySource : configPropertySources) {
  43.          configPropertySource.addChangeListener(configChangeEventPublisher);
  44.      }
  45.      }
  46.      
  47. }

从上面可知初始化时会从ConfigService远程拉取配置,并保存到内部缓存。而后续远程配置中心配置发生变化时本地会拉去最新配置并发布事件,PropertySource根据事件进行更新。

无论是开始从远程拉取配置初始化,还是后续远程配置更新,最终都是通过RemoteConfigRepository以http形式定时获取配置:

  1. public class RemoteConfigRepository extends AbstractConfigRepository implements ConfigRepository{
  2.      public RemoteConfigRepository(String namespace) {
  3.      
  4.      // 定时拉取
  5.      this.schedulePeriodicRefresh();
  6.      // 长轮询
  7.      this.scheduleLongPollingRefresh();
  8.      
  9.      }
  10.      private void schedulePeriodicRefresh() {
  11.      // 定时线程池
  12.      m_executorService.scheduleAtFixedRate(
  13.          new Runnable() {
  14.              @Override
  15.              public void run() {
  16.              // 调用父抽象类trySync()
  17.              // trySync()调用模版方法sync()
  18.              trySync();
  19.              }
  20.          }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(),
  21.          m_configUtil.getRefreshIntervalTimeUnit());
  22.      }
  23.      @Override
  24.      protected synchronized void sync() {
  25.      // 事务
  26.      Transaction transaction = Tracer.newTransaction(“Apollo.ConfigService”, “syncRemoteConfig”);
  27.      try {
  28.          ApolloConfig previous = m_configCache.get();
  29.          // http远程拉取配置
  30.          ApolloConfig current = loadApolloConfig();
  31.          // reference equals means HTTP 304
  32.          if (previous != current) {
  33.          logger.debug(“Remote Config refreshed!”);
  34.          // 设置缓存
  35.          m_configCache.set(current);
  36.          // 发布事件,该方法在父抽象类中
  37.          this.fireRepositoryChange(m_namespace, this.getConfig());
  38.          }
  39.  
  40.          if (current != null) {
  41.          Tracer.logEvent(String.format(“Apollo.Client.Configs.%s”, current.getNamespaceName()),
  42.              current.getReleaseKey());
  43.          }
  44.  
  45.          transaction.setStatus(Transaction.SUCCESS);
  46.      } catch (Throwable ex) {
  47.          transaction.setStatus(ex);
  48.          throw ex;
  49.      } finally {
  50.          transaction.complete();
  51.      }
  52.      
  53.      }

可以看到,在构造方法中,就执行了 3 个本地方法,其中就包括定时刷新和长轮询刷新。这两个功能在 apollo 的 github 文档中也有介绍:

  • 客户端和服务端保持了一个长连接,从而能第一时间获得配置更新的推送。
  • 客户端还会定时从Apollo配置中心服务端拉取应用的最新配置。
  • 这是一个fallback机制,为了防止推送机制失效导致配置不更新。
  • 客户端定时拉取会上报本地版本,所以一般情况下,对于定时拉取的操作,服务端都会返回304 – Not Modified。
  • 定时频率默认为每5分钟拉取一次,客户端也可以通过在运行时指定System Property: apollo.refreshInterval来覆盖,单位为分钟。

所以,长连接是更新配置的主要手段,然后用定时任务辅助长连接,防止长连接失败。

org.springframework.cloud.bootstrap.config

nacos实现了spring cloud config规范,规范代码的maven坐标如下:

  1.      <dependency>
  2.          <groupId>org.springframework.cloud</groupId>
  3.          <artifactId>spring-cloud-context</artifactId>
  4.          <version></version>
  5.          <scope>compile</scope>
  6.      </dependency>

这里介绍规范内容,nacos的实现略。

PropertySource

PropertySource用于存储k-v键值对,远程或本地的配置最终都转化为PropertySource,放入ConfigurableEnvironment中,通常EnumerablePropertySource中会代理一个PropertySource的list。

-1

PropertySourceLocator

规范接口主要为PropertySourceLocator接口,该接口用于定位PropertySource,注释如下:

Strategy for locating (possibly remote) property sources for the Environment. Implementations should not fail unless they intend to prevent the application from starting.

  1. public interface PropertySourceLocator {
  2.      // 实现类实现该方法
  3.      PropertySource<?> locate(Environment environment);
  4.      default Collection<PropertySource<?>> locateCollection(Environment environment) {
  5.          return locateCollection(this, environment);
  6.      }
  7.      static Collection<PropertySource<?>> locateCollection(PropertySourceLocator locator, Environment environment) {
  8.          // 调用实现类
  9.          PropertySource<?> propertySource = locator.locate(environment);
  10.          if (propertySource == null) {
  11.              return Collections.emptyList();
  12.          }
  13.          // 如果该PropertySource是代理了list的CompositePropertySource,提取全部
  14.          if (CompositePropertySource.class.isInstance(propertySource)) {
  15.              Collection<PropertySource<?>> sources = ((CompositePropertySource) propertySource).getPropertySources();
  16.              List<PropertySource<?>> filteredSources = new ArrayList<>();
  17.              for (PropertySource<?> p : sources) {
  18.                  if (!= null) {
  19.                      filteredSources.add(p);
  20.                  }
  21.              }
  22.              return filteredSources;
  23.          }
  24.          else {
  25.              return Arrays.asList(propertySource);
  26.          }
  27.      }
  28. }

PropertySourceBootstrapConfiguration

调用PropertySourceLocator接口将PropertySource加入ConfigurableEnvironment中。

  1. @Configuration(proxyBeanMethods = false)
  2. @EnableConfigurationProperties(PropertySourceBootstrapProperties.class)
  3. public class PropertySourceBootstrapConfiguration
  4.          implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
  5.      @Autowired(required = false)
  6.      private List<PropertySourceLocator> propertySourceLocators = new ArrayList<>();
  7.      public void setPropertySourceLocators(Collection<PropertySourceLocator> propertySourceLocators) {
  8.          this.propertySourceLocators = new ArrayList<>(propertySourceLocators);
  9.      }
  10.      @Override
  11.      public void initialize(ConfigurableApplicationContext applicationContext) {
  12.          List<PropertySource<?>> composite = new ArrayList<>();
  13.          // 排序
  14.          AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
  15.          boolean empty = true;
  16.          // applicationContext由回调接口提供
  17.          ConfigurableEnvironment environment = applicationContext.getEnvironment();
  18.          for (PropertySourceLocator locator : this.propertySourceLocators) {
  19.              // 调用PropertySourceLocator
  20.              Collection<PropertySource<?>> source = locator.locateCollection(environment);
  21.              
  22.              for (PropertySource<?> p : source) {
  23.                  // 是否代理了PropertySource的list做分类
  24.                  if (instanceof EnumerablePropertySource) {
  25.                      EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) p;
  26.                      sourceList.add(new BootstrapPropertySource<>(enumerable));
  27.                  }
  28.                  else {
  29.                      sourceList.add(new SimpleBootstrapPropertySource(p));
  30.                  }
  31.              }
  32.              composite.addAll(sourceList);
  33.              empty = false;
  34.          }
  35.          if (!empty) {
  36.              // 获取 ConfigurableEnvironment中的MutablePropertySources
  37.              MutablePropertySources propertySources = environment.getPropertySources();
  38.              
  39.              // 执行插入到ConfigurableEnvironment的MutablePropertySources
  40.              insertPropertySources(propertySources, composite);
  41.              
  42.          }
  43.      }
  44. }

总结

可以看到从远程获取配置都是通过向ConfigurableEnvironment插入从远程获取的数据转化的PropertySource。而从远程获取就涉及到长轮询、本地缓存等内容,设计都比较一致。

到此这篇关于Spring远程加载配置的实现方法详解的文章就介绍到这了,更多相关Spring远程加载配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论