Apollo 源码解析 —— Client 轮询配置

Apollo-client加载数据解析 如需参考源码解析,请访问:https://gitee.com/lidishan/apollo-code-analysis 阅读前声明:本文不做相关用法说明,只解析Apollo-client源码 阅读本文前请参考《Apollo-client 初始化入口流程解析》 上面解析到了initialize()初始化,其是通过ConfigService.getConfig()来加载数据,那这个调用方式是怎么加载的?见下面 实时获取apollo配置解析ConfigService.getConfig() 如何使用?例子如下 阅读详情

点击上方“芋道源码”,选择“设为星标”

管她前浪,还是后浪?

能浪的浪,才是好浪!

每天 8:55 更新文章,每天掉亿点点头发...

源码精品专栏

 

摘要: 原创出处 http://www.iocoder.cn/Apollo/client-polling-config/ 「芋道源码」欢迎转载,保留摘要,谢谢!

  • 1. 概述

  • 2. ConfigRepository

  • 3. RemoteConfigLongPollService

  • 4. SchedulePolicy

  • 666. 彩蛋


1. 概述

老艿艿:本系列假定胖友已经阅读过 《Apollo 官方 wiki 文档》  。

本文分享 Client 如何通过轮询的方式,从 Config Service 读取配置。Client 的轮询包括两部分:

  1. RemoteConfigRepository ,定时轮询 Config Service 的配置读取 /configs/{appId}/{clusterName}/{namespace:.+} 接口。

  • 接口的逻辑,在 《Apollo 源码解析 —— Config Service 配置读取接口》  有详细解析。

  • RemoteConfigLongPollService ,长轮询 Config Service 的配置变更通知 /notifications/v2 接口。

    • 当有新的通知时,触发 RemoteConfigRepository ,立即轮询 Config Service 的配置读取 /configs/{appId}/{clusterName}/{namespace:.+} 接口。

    • 接口的逻辑,在 《Apollo 源码解析 —— Config Service 通知配置变化》 有详细解析。

    整体流程如下图:

    • 一个 Namespace 对应一个 RemoteConfigRepository 。

    • 多个 RemoteConfigRepository ,注册到全局唯一的 RemoteConfigLongPollService 中。

    为什么是这样的设计呢?老艿艿请教了 Apollo 的作者宋老师。聊天内容如下,非常感谢:

    • 老艿艿:

      • https://github.com/ctripcorp/apollo/issues/652

      • 看这个 issue 问了

      • 问题:非常感谢。为什么不在 long polling 的返回结果中直接返回更新的结果呢?

    • 回答:这样推送消息就是有状态了,做不到幂等了,会带来很多问题。

    • [呲牙] 周末打扰哈。带来的问题主要是哪些哈?

    • 张大佬:

      • 可能会有数据的丢失,如果使用只推送变更通知的话,即使丢失了,还是能在下一次变更的时候达到一个一致的状态

    • 宋老师:

      • @老艿艿 主要是幂等考虑

      • 加载配置接口是幂等的,推送配置的话就做不到了,因为和推送顺序相关

    • 老艿艿:

      • 推送顺序指的是?

    • 张大佬:

      • 我想的是,比如两次修改操作的通知,由于网络问题,客户端接收到的顺序可能是反的,如果这两次修改的是同一个key,就有问题了。

    • 老艿艿:

      • 从目前代码看下来,长轮询发起,同时只会有一个,应该不会同时两个通知呀。

      • 现在 client 是一个长轮询+定时轮询,是不是这两个会有互相的影响。

    • 张大佬:

      • @宋老师 嗯嗯

    • 宋老师:

      • 目前推送是单连接走http的,所以问题可能不大,不过在设计上而言是有这个问题的,比如如果推送是走的tcp长连接的话。另外,长轮询和推送之间也会有冲突,如果连续两次配置变化,就可能造成双写。还有一点,就是保持逻辑的简单,目前的做法推送只负责做简单的通知,不需要去计算客户端的配置应该是什么,因为计算逻辑挺复杂的,需要考虑集群,关联,灰度等。

    • 老艿艿:

      • 现在的设计思路上,是不是可以理解.

      • 1、client 的定时轮询,可以保持最终一致。

      • 2、client 的长轮询,是定时轮训的“实时”补充,通过这样的方式,让流程统一?

    • 宋老师:

      • 总而言之,就是在满足幂等性,实时性的基础上保持设计的简单

      • 是的,推拉结合

    • 张大佬:

      • 长轮询个推送直接的冲突没太理解

      • 有没有可能有这种问题,一次长轮询中消息丢失了,但是长轮询还在

    • 老艿艿:

      • 这个时候,client 是没办法判断哪个配置信息是新的。

      • @张大佬 我认为是可能的,这个时候,client 可以发起新的长轮询。

    1. 定时轮训,里面也拿到配置信息

    1. 长轮询的通知里面,带有配置信息

    • 宋大佬:

      • @张大佬 长轮询和推送的冲突,这个更正为定时轮询和推送的冲突

    • 老艿艿:

      • 通知是定时轮询配置的补充。有了通知,立马轮询。不用在定时了

    • 张大佬:

      • get

    • 老艿艿:

      • 谢谢宋老师和张大佬[坏笑][坏笑]

    2. ConfigRepository

    com.ctrip.framework.apollo.internals.ConfigRepository ,配置 Repository 接口。代码如下:

    public interface ConfigRepository {
    
        /**
         * Get the config from this repository.
         *
         * @return config
         */
        Properties getConfig();
    
        /**
         * Set the fallback repo for this repository.
         *
         * @param upstreamConfigRepository the upstream repo
         */
        void setUpstreamRepository(ConfigRepository upstreamConfigRepository);
    
        /**
         * Add change listener.
         *
         * @param listener the listener to observe the changes
         */
        void addChangeListener(RepositoryChangeListener listener);
    
        /**
         * Remove change listener.
         *
         * @param listener the listener to remove
         */
        void removeChangeListener(RepositoryChangeListener listener);
    
    }
    
    • ConfigRepository ,作为 Client 的 Repository ( 类似 DAO ) ,读取配置。

    • #getConfig() 方法,读取配置。

    • #setUpstreamRepository(ConfigRepository) 方法,设置上游的 Repository 。主要用于 LocalFileConfigRepository ,从 Config Service 读取配置,缓存在本地文件。

    • RepositoryChangeListener ,监听 Repository 的配置的变化。????

      • #addChangeListener(RepositoryChangeListener)

      • #removeChangeListener(RepositoryChangeListener)


    子类如下图所示:

    • 本文不分享 LocalFileConfigRepository 。

    2.1 AbstractConfigRepository

    com.ctrip.framework.apollo.internals.AbstractConfigRepository ,实现 ConfigRepository 接口,配置 Repository 抽象类。

    2.1.1 同步配置

    /**
     * 尝试同步
     *
     * @return 是否同步成功
     */
    protected boolean trySync() {
        try {
            // 同步
            sync();
            // 返回同步成功
            return true;
        } catch (Throwable ex) {
            // 【TODO 6001】Tracer 日志
            Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
            logger.warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil.getDetailMessage(ex));
        }
        // 返回同步失败
        return false;
    }
    
    /**
     * 同步配置
     */
    protected abstract void sync();
    
    • #sync() 抽象方法,同步配置。

    2.1.2 监听器

    /**
     * RepositoryChangeListener 数组
     */
    private List<RepositoryChangeListener> m_listeners = Lists.newCopyOnWriteArrayList();
    
    @Override
    public void addChangeListener(RepositoryChangeListener listener) {
        if (!m_listeners.contains(listener)) {
            m_listeners.add(listener);
        }
    }
    
    @Override
    public void removeChangeListener(RepositoryChangeListener listener) {
        m_listeners.remove(listener);
    }
    
    /**
     * 触发监听器们
     *
     * @param namespace Namespace 名字
     * @param newProperties 配置
     */
    protected void fireRepositoryChange(String namespace, Properties newProperties) {
        // 循环 RepositoryChangeListener 数组
        for (RepositoryChangeListener listener : m_listeners) {
            try {
                // 触发监听器
                listener.onRepositoryChange(namespace, newProperties);
            } catch (Throwable ex) {
                // 【TODO 6001】Tracer 日志
                Tracer.logError(ex);
                logger.error("Failed to invoke repository change listener {}", listener.getClass(), ex);
            }
        }
    }
    

    2.2 RemoteConfigRepository

    com.ctrip.framework.apollo.internals.RemoteConfigRepository ,实现 AbstractConfigRepository 抽象类,远程配置 Repository 。实现从 Config Service 拉取配置,并缓存在内存中。并且,定时 + 实时刷新缓存。

    2.2.1 构造方法

    private static final Logger logger = LoggerFactory.getLogger(RemoteConfigRepository.class);
    private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
    private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("=");
    
    private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper();
    private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();
    
    /**
     * 远程配置长轮询服务
     */
    private RemoteConfigLongPollService remoteConfigLongPollService;
    /**
     * 指向 ApolloConfig 的 AtomicReference ,缓存配置
     */
    private volatile AtomicReference<ApolloConfig> m_configCache;
    /**
     * Namespace 名字
     */
    private final String m_namespace;
    /**
     * ScheduledExecutorService 对象
     */
    private final static ScheduledExecutorService m_executorService;
    /**
     * 指向 ServiceDTO( Config Service 信息) 的 AtomicReference
     */
    private AtomicReference<ServiceDTO> m_longPollServiceDto;
    /**
     * 指向 ApolloNotificationMessages 的 AtomicReference
     */
    private AtomicReference<ApolloNotificationMessages> m_remoteMessages;
    /**
     * 加载配置的 RateLimiter
     */
    private RateLimiter m_loadConfigRateLimiter;
    /**
     * 是否强制拉取缓存的标记
     *
     * 若为 true ,则多一轮从 Config Service 拉取配置
     * 为 true 的原因,RemoteConfigRepository 知道 Config Service 有配置刷新
     */
    private AtomicBoolean m_configNeedForceRefresh;
    /**
     * 失败定时重试策略,使用 {@link ExponentialSchedulePolicy}
     */
    private SchedulePolicy m_loadConfigFailSchedulePolicy;
    private Gson gson;
    private ConfigUtil m_configUtil;
    private HttpUtil m_httpUtil;
    private ConfigServiceLocator m_serviceLocator;
    
    static {
        // 单线程池
        m_executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("RemoteConfigRepository", true));
    }
    
    /**
     * Constructor.
     *
     * @param namespace the namespace
     */
    public RemoteConfigRepository(String namespace) {
        m_namespace = namespace;
        m_configCache = new AtomicReference<>();
        m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
        m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
        m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
        remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
        m_longPollServiceDto = new AtomicReference<>();
        m_remoteMessages = new AtomicReference<>();
        m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
        m_configNeedForceRefresh = new AtomicBoolean(true);
        m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(), m_configUtil.getOnErrorRetryInterval() * 8);
        gson = new Gson();
        // 尝试同步配置
        this.trySync();
        // 初始化定时刷新配置的任务
        this.schedulePeriodicRefresh();
        // 注册自己到 RemoteConfigLongPollService 中,实现配置更新的实时通知
        this.scheduleLongPollingRefresh();
    }
    
    • 基础属性

      • m_namespace 属性,Namespace 名字。一个 RemoteConfigRepository 对应一个 Namespace 。

      • m_configCache 属性,指向 ApolloConfig 的 AtomicReference ,缓存配置。

    • 轮询属性

      • m_remoteMessages 属性,指向 ApolloNotificationMessages 的 AtomicReference 。

      • m_executorService 属性,ScheduledExecutorService 对象,线程大小为 1 。

      • m_loadConfigRateLimiter 属性,加载配置的 RateLimiter 。

      • m_loadConfigFailSchedulePolicy ,失败定时重试策略,使用 ExponentialSchedulePolicy 实现类,区间范围是 [1, 8] 秒。详细解析,见 「4. SchedulePolicy」 。

    • 通知属性

      • 若为 true ,则多一轮从 Config Service 拉取配置。

      • 为 true 的原因,RemoteConfigRepository 知道 Config Service 有配置刷新,例如有新的通知的情况下。

      • 比较绕,下面看了代码会更加好理解。

      • remoteConfigLongPollService 属性,远程配置长轮询服务。

      • m_longPollServiceDto 属性,长轮询到通知的 Config Service 信息。在下一次轮询配置时,优先从该 Config Service 请求。

      • m_configNeedForceRefresh 属性,是否强制拉取缓存的标记。

    • 构造方法

      • 当 RemoteConfigLongPollService 长轮询到该 RemoteConfigRepository 的 Namespace 下的配置更新时,会回调 #onLongPollNotified(ServiceDTO, ApolloNotificationMessages) 方法,在 「2.2.4 onLongPollNotified」 中,详细解析。

      • 每 5 分钟,调用 #trySync() 方法,同步配置。

      • 调用 #trySync() 方法,尝试同步配置,作为初次的配置缓存初始化。

      • 调用 #schedulePeriodicRefresh() 方法,初始化定时刷新配置的任务。代码如下:

        private void schedulePeriodicRefresh() {
            logger.debug("Schedule periodic refresh with interval: {} {}", m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit());
            // 创建定时任务,定时刷新配置
            m_executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    // 【TODO 6001】Tracer 日志
                    Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace));
                    logger.debug("refresh config for namespace: {}", m_namespace);
                    // 尝试同步配置
                    trySync();
                    // 【TODO 6001】Tracer 日志
                    Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION);
                }
            }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit());
        }
        
      • 调用 #scheduleLongPollingRefresh() 方法,将自己注册到 RemoteConfigLongPollService 中,实现配置更新的实时通知。代码如下:

        private void scheduleLongPollingRefresh() {
            remoteConfigLongPollService.submit(m_namespace, this);
        }
        

    2.2.2 getConfigServices

    #getConfigServices() 方法,获得所有 Config Service 信息。代码如下:

    private List<ServiceDTO> getConfigServices() {
        List<ServiceDTO> services = m_serviceLocator.getConfigServices();
        if (services.size() == 0) {
            throw new ApolloConfigException("No available config service");
        }
        return services;
    }
    
    • 通过 ConfigServiceLocator ,可获得 Config Service 集群的地址们。在后续和注册发现相关的文章,详细解析 ConfigServiceLocator 。这里,我们只需要有这么一回事即可。

    2.2.3 assembleQueryConfigUrl

    #assembleQueryConfigUrl() 方法,组装轮询 Config Service 的配置读取 /configs/{appId}/{clusterName}/{namespace:.+} 接口的 URL ,代码如下:

    String assembleQueryConfigUrl(String uri, String appId, String cluster, String namespace,
                                  String dataCenter, ApolloNotificationMessages remoteMessages, ApolloConfig previousConfig) {
        String path = "configs/%s/%s/%s"; // /configs/{appId}/{clusterName}/{namespace:.+}
        List<String> pathParams = Lists.newArrayList(pathEscaper.escape(appId), pathEscaper.escape(cluster), pathEscaper.escape(namespace));
        Map<String, String> queryParams = Maps.newHashMap();
        // releaseKey
        if (previousConfig != null) {
            queryParams.put("releaseKey", queryParamEscaper.escape(previousConfig.getReleaseKey()));
        }
        // dataCenter
        if (!Strings.isNullOrEmpty(dataCenter)) {
            queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter));
        }
        // ip
        String localIp = m_configUtil.getLocalIp();
        if (!Strings.isNullOrEmpty(localIp)) {
            queryParams.put("ip", queryParamEscaper.escape(localIp));
        }
        // messages
        if (remoteMessages != null) {
            queryParams.put("messages", queryParamEscaper.escape(gson.toJson(remoteMessages)));
        }
        // 格式化 URL
        String pathExpanded = String.format(path, pathParams.toArray());
        // 拼接 Query String
        if (!queryParams.isEmpty()) {
            pathExpanded += "?" + MAP_JOINER.join(queryParams);
        }
        // 拼接最终的请求 URL
        if (!uri.endsWith("/")) {
            uri += "/";
        }
        return uri + pathExpanded;
    }
    

    ###2.2.4 onLongPollNotified

    #onLongPollNotified(ServiceDTO longPollNotifiedServiceDto, ApolloNotificationMessages remoteMessages) 方法,当长轮询到配置更新时,发起同步配置的任务。代码如下:

      1: public void onLongPollNotified(ServiceDTO longPollNotifiedServiceDto, ApolloNotificationMessages remoteMessages) {
      2:     // 设置长轮询到配置更新的 Config Service 。下次同步配置时,优先读取该服务
      3:     m_longPollServiceDto.set(longPollNotifiedServiceDto);
      4:     // 设置 m_remoteMessages
      5:     m_remoteMessages.set(remoteMessages);
      6:     // 提交同步任务
      7:     m_executorService.submit(new Runnable() {
      8:
      9:         @Override
     10:         public void run() {
     11:             // 设置 m_configNeedForceRefresh 为 true
     12:             m_configNeedForceRefresh.set(true);
     13:             // 尝试同步配置
     14:             trySync();
     15:         }
     16:
     17:     });
     18: }
    
    • 第 3 行:设置长轮询到配置更新的 Config Service 。下次同步配置时,优先读取该服务。

    • 第 5 行:设置 m_remoteMessages 。

    • 第 6 至 17 行:提交配置同步任务。

      • 第 12 行:设置 m_configNeedForceRefresh 为 true 。

      • 第 14 行:调用 #trySync() 方法,同步配置。

    2.2.5 sync

    #sync() 实现方法,从 Config Service 同步配置。代码如下:

      1: @Override
      2: protected synchronized void sync() {
      3:     // 【TODO 6001】Tracer 日志
      4:     Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");
      5:     try {
      6:         // 获得缓存的 ApolloConfig 对象
      7:         ApolloConfig previous = m_configCache.get();
      8:         // 从 Config Service 加载 ApolloConfig 对象
      9:         ApolloConfig current = loadApolloConfig();
     10:
     11:         // reference equals means HTTP 304
     12:         // 若不相等,说明更新了,设置到缓存中
     13:         if (previous != current) {
     14:             logger.debug("Remote Config refreshed!");
     15:             // 设置到缓存
     16:             m_configCache.set(current);
     17:             // 发布 Repository 的配置发生变化,触发对应的监听器们
     18:             super.fireRepositoryChange(m_namespace, this.getConfig());
     19:         }
     20:         // 【TODO 6001】Tracer 日志
     21:         if (current != null) {
     22:             Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()), current.getReleaseKey());
     23:         }
     24:         // 【TODO 6001】Tracer 日志
     25:         transaction.setStatus(Transaction.SUCCESS);
     26:     } catch (Throwable ex) {
     27:         // 【TODO 6001】Tracer 日志
     28:         transaction.setStatus(ex);
     29:         throw ex;
     30:     } finally {
     31:         // 【TODO 6001】Tracer 日志
     32:         transaction.complete();
     33:     }
     34: }
    
    • 第 7 行:获得缓存 m_configCache 的 ApolloConfig 对象。

    • 第 9 行:调用 #loadApolloConfig() 方法,从 Config Service 加载 ApolloConfig 对象。详细解析,见

    • 第 13 至 19 行:若缓存的和加载的 ApolloConfig 对象不同,说明更新了,设置缓存中。

      • 第 16 行:设置加载到的  ApolloConfig 到缓存 m_configCache 中。

      • 第 18 行:调用 #fireRepositoryChange(m_namespace, ApolloConfig) 方法,发布 Repository 的配置发生变化,触发对应的监听器们。。详细解析,见 「2.2.6  loadApolloConfig」 。

    2.2.6 loadApolloConfig

    #loadApolloConfig() 方法,从 Config Service 加载 ApolloConfig 对象。代码如下:

      1: private ApolloConfig loadApolloConfig() {
      2:     // 限流
      3:     if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
      4:         // wait at most 5 seconds
      5:         try {
      6:             TimeUnit.SECONDS.sleep(5);
      7:         } catch (InterruptedException e) {
      8:         }
      9:     }
     10:     // 获得 appId cluster dataCenter 配置信息
     11:     String appId = m_configUtil.getAppId();
     12:     String cluster = m_configUtil.getCluster();
     13:     String dataCenter = m_configUtil.getDataCenter();
     14:     Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
     15:     // 计算重试次数
     16:     int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
     17:     long onErrorSleepTime = 0; // 0 means no sleep
     18:     Throwable exception = null;
     19:     // 获得所有的 Config Service 的地址
     20:     List<ServiceDTO> configServices = getConfigServices();
     21:     String url = null;
     22:     // 循环读取配置重试次数直到成功。每一次,都会循环所有的 ServiceDTO 数组。
     23:     for (int i = 0; i < maxRetries; i++) {
     24:         // 随机所有的 Config Service 的地址
     25:         List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
     26:         Collections.shuffle(randomConfigServices);
     27:         // 优先访问通知配置变更的 Config Service 的地址。并且,获取到时,需要置空,避免重复优先访问。
     28:         // Access the server which notifies the client first
     29:         if (m_longPollServiceDto.get() != null) {
     30:             randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
     31:         }
     32:         // 循环所有的 Config Service 的地址
     33:         for (ServiceDTO configService : randomConfigServices) {
     34:             // sleep 等待,下次从 Config Service 拉取配置
     35:             if (onErrorSleepTime > 0) {
     36:                 logger.warn("Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}", onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
     37:                 try {
     38:                     m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
     39:                 } catch (InterruptedException e) {
     40:                     //ignore
     41:                 }
     42:             }
     43:             // 组装查询配置的地址
     44:             url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace, dataCenter, m_remoteMessages.get(), m_configCache.get());
     45:
     46:             logger.debug("Loading config from {}", url);
     47:             // 创建 HttpRequest 对象
     48:             HttpRequest request = new HttpRequest(url);
     49:
     50:             // 【TODO 6001】Tracer 日志
     51:             Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
     52:             transaction.addData("Url", url);
     53:             try {
     54:                 // 发起请求,返回 HttpResponse 对象
     55:                 HttpResponse<ApolloConfig> response = m_httpUtil.doGet(request, ApolloConfig.class);
     56:                 // 设置 m_configNeedForceRefresh = false
     57:                 m_configNeedForceRefresh.set(false);
     58:                 // 标记成功
     59:                 m_loadConfigFailSchedulePolicy.success();
     60:
     61:                 // 【TODO 6001】Tracer 日志
     62:                 transaction.addData("StatusCode", response.getStatusCode());
     63:                 transaction.setStatus(Transaction.SUCCESS);
     64:
     65:                 // 无新的配置,直接返回缓存的 ApolloConfig 对象
     66:                 if (response.getStatusCode() == 304) {
     67:                     logger.debug("Config server responds with 304 HTTP status code.");
     68:                     return m_configCache.get();
     69:                 }
     70:
     71:                 // 有新的配置,进行返回新的 ApolloConfig 对象
     72:                 ApolloConfig result = response.getBody();
     73:                 logger.debug("Loaded config for {}: {}", m_namespace, result);
     74:                 return result;
     75:             } catch (ApolloConfigStatusCodeException ex) {
     76:                 ApolloConfigStatusCodeException statusCodeException = ex;
     77:                 // 若返回的状态码是 404 ,说明查询配置的 Config Service 不存在该 Namespace 。
     78:                 // config not found
     79:                 if (ex.getStatusCode() == 404) {
     80:                     String message = String.format("Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
     81:                                     "please check whether the configs are released in Apollo!", appId, cluster, m_namespace);
     82:                     statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(), message);
     83:                 }
     84:                 // 【TODO 6001】Tracer 日志
     85:                 Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
     86:                 transaction.setStatus(statusCodeException);
     87:                 // 设置最终的异常
     88:                 exception = statusCodeException;
     89:             } catch (Throwable ex) {
     90:                 // 【TODO 6001】Tracer 日志
     91:                 Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
     92:                 transaction.setStatus(ex);
     93:                 // 设置最终的异常
     94:                 exception = ex;
     95:             } finally {
     96:                 // 【TODO 6001】Tracer 日志
     97:                 transaction.complete();
     98:             }
     99:             // 计算延迟时间
    100:             // if force refresh, do normal sleep, if normal config load, do exponential sleep
    101:             onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() : m_loadConfigFailSchedulePolicy.fail();
    102:         }
    103:
    104:     }
    105:     // 若查询配置失败,抛出 ApolloConfigException 异常
    106:     String message = String.format("Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s", appId, cluster, m_namespace, url);
    107:     throw new ApolloConfigException(message, exception);
    108: }
    
    • 第 3 至 9 行:调用 RateLimiter#tryAcquire(long timeout, TimeUnit unit) 方法,判断是否被限流。若限流,sleep 5 秒,避免对 Config Service 请求过于频繁。

    • 第 10 至 13 行:获得 appId cluster dataCenter 配置信息。

    • 第 16 行:计算重试次数。若 m_configNeedForceRefresh 为 true ,代表强制刷新配置,会多重试一次。

    • 第 20 行:调用 #getConfigServices() 方法,获得所有的 Config Service 的地址。

    • ========== 第一层循环 ==========

    • 第 23 至 104 行:循环读取配置重试次数直到成功。每一次,都会循环所有的 ServiceDTO 数组。

    • 第 24 至 26 行:创建新的 Config Service 数组,并随机打乱。因为【第 29 至 31 行】可能会添加新的 Config Service 元素,如果不创建新的数组,会修改了原有数组。

    • 第 27 至 31 行:若 m_longPollServiceDto 非空,优先访问通知配置变更的 Config Service 的地址。并且,获取到时,需要置空,避免重复优先访问。

    • ========== 第二层循环 ==========

    • 第 33 至 102 行:循环所有的 Config Service 的地址,读取配置重试次数直到成功。

    • 第 34 至 42 行:若 onErrorSleepTime 大于零,sleep 等待,下次从 Config Service 拉取配置。在【第 101 行】,若请求失败一次 Config Service 时,会计算一次下一次请求的延迟时间。因为是每次请求失败一次 Config Service 时就计算一次,所以延迟时间的上限为 8 秒,比较短。

    • 第 44 行:调用 #assembleQueryConfigUrl(...) 方法,组装查询配置的地址。

    • 第 48 行:创建 HttpRequest 对象。

    • 第 55 行:调用 HttpUtil#doGet(request, Class) 方法,发起请求,返回 HttpResponse 对象。

    • 第 57 行:设置 m_configNeedForceRefresh 为 false 。

    • 第 59 行:调用 SchedulePolicy#success() 方法,标记成功。

    • 第 65 至 69 行:若返回的状态码是 304 ,无新的配置,直接返回缓存的 ApolloConfig 对象。

    • 第 71 至 74 行:有新的配置,创建 ApolloConfig 对象,并返回。

    • 第 75 至 94 行:异常相关的处理,胖友自己看注释。

    • 第 101 行:计算延迟时间。若 m_configNeedForceRefresh 为:

      • true 时,调用 ConfigUtil#getOnErrorRetryInterval() 方法,返回 2 秒。因为已经知道有配置更新,所以减短重试间隔。

      • false 时,调用 SchedulePolicy#fail() 方法,计算下次重试延迟时间。

    • ========== 最外层 ==========

    • 第 105 至 107 行:若查询配置失败,抛出 ApolloConfigException 异常。

    2.2.7 getConfig

    #getConfig() 实现方法,获得配置。代码如下:

      1: @Override
      2: public Properties getConfig() {
      3:     // 如果缓存为空,强制从 Config Service 拉取配置
      4:     if (m_configCache.get() == null) {
      5:         this.sync();
      6:     }
      7:     // 转换成 Properties 对象,并返回
      8:     return transformApolloConfigToProperties(m_configCache.get());
      9: }
    
    • 第 3 至 6 行:若果缓存为空,调用 #sync() 方法,强制从 Config Service 拉取配置。

    • 第 8 行:调用 #transformApolloConfigToProperties(ApolloConfig) 对象,转换成 Properties 对象,并返回。代码如下:

      private Properties transformApolloConfigToProperties(ApolloConfig apolloConfig) {
          Properties result = new Properties();
          result.putAll(apolloConfig.getConfigurations());
          return result;
      }
      

    3. RemoteConfigLongPollService

    com.ctrip.framework.apollo.internals.RemoteConfigLongPollService ,远程配置长轮询服务。负责长轮询 Config Service 的配置变更通知 /notifications/v2 接口。当有新的通知时,触发 RemoteConfigRepository ,立即轮询 Config Service 的配置读取 /configs/{appId}/{clusterName}/{namespace:.+} 接口。

    3.1 构造方法

    private static final Logger logger = LoggerFactory.getLogger(RemoteConfigLongPollService.class);
    
    private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
    private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("=");
    private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();
    
    private static final long INIT_NOTIFICATION_ID = ConfigConsts.NOTIFICATION_ID_PLACEHOLDER;
    // 90 seconds, should be longer than server side's long polling timeout, which is now 60 seconds
    private static final int LONG_POLLING_READ_TIMEOUT = 90 * 1000;
    
    /**
     * 长轮询 ExecutorService
     */
    private final ExecutorService m_longPollingService;
    /**
     * 是否停止长轮询的标识
     */
    private final AtomicBoolean m_longPollingStopped;
    /**
     * 失败定时重试策略,使用 {@link ExponentialSchedulePolicy}
     */
    private SchedulePolicy m_longPollFailSchedulePolicyInSecond;
    /**
     * 长轮询的 RateLimiter
     */
    private RateLimiter m_longPollRateLimiter;
    /**
     * 是否长轮询已经开始的标识
     */
    private final AtomicBoolean m_longPollStarted;
    /**
     * 长轮询的 Namespace Multimap 缓存
     *
     * 通过 {@link #submit(String, RemoteConfigRepository)} 添加 RemoteConfigRepository 。
     *
     * KEY:Namespace 的名字
     * VALUE:RemoteConfigRepository 集合
     */
    private final Multimap<String, RemoteConfigRepository> m_longPollNamespaces;
    /**
     * 通知编号 Map 缓存
     *
     * KEY:Namespace 的名字
     * VALUE:最新的通知编号
     */
    private final ConcurrentMap<String, Long> m_notifications;
    /**
     * 通知消息 Map 缓存
     *
     * KEY:Namespace 的名字
     * VALUE:ApolloNotificationMessages 对象
     */
    private final Map<String, ApolloNotificationMessages> m_remoteNotificationMessages;//namespaceName -> watchedKey -> notificationId
    private Type m_responseType;
    private Gson gson;
    private ConfigUtil m_configUtil;
    private HttpUtil m_httpUtil;
    private ConfigServiceLocator m_serviceLocator;
    
    public RemoteConfigLongPollService() {
        m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
        m_longPollingStopped = new AtomicBoolean(false);
        m_longPollingService = Executors.newSingleThreadExecutor(ApolloThreadFactory.create("RemoteConfigLongPollService", true));
        m_longPollStarted = new AtomicBoolean(false);
        m_longPollNamespaces = Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
        m_notifications = Maps.newConcurrentMap();
        m_remoteNotificationMessages = Maps.newConcurrentMap();
        m_responseType = new TypeToken<List<ApolloConfigNotification>>() {}.getType();
        gson = new Gson();
        m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
        m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
        m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
        m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
    }
    
    • 基础属性

      • m_longPollNamespaces 属性,注册的长轮询的 Namespace Multimap 缓存。

      • m_notifications 属性,通知编号 Map 缓存。

      • m_remoteNotificationMessages 属性,通知消息 Map 缓存。

    • 轮询属性

      • m_longPollingService 属性,长轮询 ExecutorService ,线程大小为 1 。

      • m_longPollingStopped 属性,是否停止长轮询的标识。

      • m_longPollStarted 属性,是否长轮询已经开始的标识。

      • m_loadConfigRateLimiter 属性,加载配置的 RateLimiter 。

      • m_longPollFailSchedulePolicyInSecond ,失败定时重试策略,使用 ExponentialSchedulePolicy 实现类,区间范围是 [1, 120] 秒。详细解析,见 「4. SchedulePolicy」  。

    3.2 getConfigServices

    同 「2.2 getConfigServices」  的代码。

    3.3 assembleLongPollRefreshUrl

    #assembleLongPollRefreshUrl(...) 方法,长轮询 Config Service 的配置变更通知 /notifications/v2 接口的 URL ,代码如下:

    String assembleLongPollRefreshUrl(String uri, String appId, String cluster, String dataCenter, Map<String, Long> notificationsMap) {
        Map<String, String> queryParams = Maps.newHashMap();
        queryParams.put("appId", queryParamEscaper.escape(appId));
        queryParams.put("cluster", queryParamEscaper.escape(cluster));
        // notifications
        queryParams.put("notifications", queryParamEscaper.escape(assembleNotifications(notificationsMap)));
        // dataCenter
        if (!Strings.isNullOrEmpty(dataCenter)) {
            queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter));
        }
        // ip
        String localIp = m_configUtil.getLocalIp();
        if (!Strings.isNullOrEmpty(localIp)) {
            queryParams.put("ip", queryParamEscaper.escape(localIp));
        }
        // 创建 Query String
        String params = MAP_JOINER.join(queryParams);
        // 拼接 URL
        if (!uri.endsWith("/")) {
            uri += "/";
        }
        return uri + "notifications/v2?" + params;
    }
    
    String assembleNotifications(Map<String, Long> notificationsMap) {
        // 创建 ApolloConfigNotification 数组
        List<ApolloConfigNotification> notifications = Lists.newArrayList();
        // 循环,添加 ApolloConfigNotification 对象
        for (Map.Entry<String, Long> entry : notificationsMap.entrySet()) {
            ApolloConfigNotification notification = new ApolloConfigNotification(entry.getKey(), entry.getValue());
            notifications.add(notification);
        }
        // JSON 化成字符串
        return gson.toJson(notifications);
    }
    

    3.4 submit

    #submit(namespace, RemoteConfigRepository) 方法,提交 RemoteConfigRepository 到长轮询任务。代码如下:

      1: public boolean submit(String namespace, RemoteConfigRepository remoteConfigRepository) {
      2:     // 添加到 m_longPollNamespaces 中
      3:     boolean added = m_longPollNamespaces.put(namespace, remoteConfigRepository);
      4:     // 添加到 m_notifications 中
      5:     m_notifications.putIfAbsent(namespace, INIT_NOTIFICATION_ID);
      6:     // 若未启动长轮询定时任务,进行启动
      7:     if (!m_longPollStarted.get()) {
      8:         startLongPolling();
      9:     }
     10:     return added;
     11: }
    
    • 第 3 行:添加到 m_longPollNamespaces.put 中。

    • 第 5 行:添加到 m_notifications 中。

    • 第 6 至 9 行:若未启动长轮询定时任务,调用 #startLongPolling() 方法,进行启动。

    3.5 startLongPolling

    #startLongPolling() 方法,启动长轮询任务。代码如下:

      1: private void startLongPolling() {
      2:     // CAS 设置长轮询任务已经启动。若已经启动,不重复启动。
      3:     if (!m_longPollStarted.compareAndSet(false, true)) {
      4:         //already started
      5:         return;
      6:     }
      7:     try {
      8:         // 获得 appId cluster dataCenter 配置信息
      9:         final String appId = m_configUtil.getAppId();
     10:         final String cluster = m_configUtil.getCluster();
     11:         final String dataCenter = m_configUtil.getDataCenter();
     12:         // 获得长轮询任务的初始化延迟时间,单位毫秒。
     13:         final long longPollingInitialDelayInMills = m_configUtil.getLongPollingInitialDelayInMills();
     14:         // 提交长轮询任务。该任务会持续且循环执行。
     15:         m_longPollingService.submit(new Runnable() {
     16:             @Override
     17:             public void run() {
     18:                 // 初始等待
     19:                 if (longPollingInitialDelayInMills > 0) {
     20:                     try {
     21:                         logger.debug("Long polling will start in {} ms.", longPollingInitialDelayInMills);
     22:                         TimeUnit.MILLISECONDS.sleep(longPollingInitialDelayInMills);
     23:                     } catch (InterruptedException e) {
     24:                         //ignore
     25:                     }
     26:                 }
     27:                 // 执行长轮询
     28:                 doLongPollingRefresh(appId, cluster, dataCenter);
     29:             }
     30:         });
     31:     } catch (Throwable ex) {
     32:         // 设置 m_longPollStarted 为 false
     33:         m_longPollStarted.set(false);
     34:         // 【TODO 6001】Tracer 日志
     35:         ApolloConfigException exception = new ApolloConfigException("Schedule long polling refresh failed", ex);
     36:         Tracer.logError(exception);
     37:         logger.warn(ExceptionUtil.getDetailMessage(exception));
     38:     }
     39: }
    
    • 第 2 至 6 行:CAS 设置长轮询任务已经启动。若已经启动,不重复启动。

    • 第 8 至 11 行:获得 appId cluster dataCenter 配置信息。

    • 第 13 行:调用 ConfigUtil#getLongPollingInitialDelayInMills() 方法,获得长轮询任务的初始化延迟时间,单位毫秒。默认,2000 毫秒。

    • 第 14 至 30 行:提交长轮询任务。该任务会持续且循环执行。

      • 第 18 至 26 行:sleep ,初始等待。

      • 第 28 行:调用 #doLongPollingRefresh(appId, cluster, dataCenter) 方法,执行长轮询任务。

    • 第 31 至 38 行:初始化失败的异常处理,胖友自己看代码注释。

    3.6 doLongPollingRefresh

    #doLongPollingRefresh() 方法,持续执行长轮询。代码如下:

      1: private void doLongPollingRefresh(String appId, String cluster, String dataCenter) {
      2:     final Random random = new Random();
      3:     ServiceDTO lastServiceDto = null;
      4:     // 循环执行,直到停止或线程中断
      5:     while (!m_longPollingStopped.get() && !Thread.currentThread().isInterrupted()) {
      6:         // 限流
      7:         if (!m_longPollRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
      8:             // wait at most 5 seconds
      9:             try {
     10:                 TimeUnit.SECONDS.sleep(5);
     11:             } catch (InterruptedException e) {
     12:             }
     13:         }
     14:         // 【TODO 6001】Tracer 日志
     15:         Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "pollNotification");
     16:         String url = null;
     17:         try {
     18:             // 获得 Config Service 的地址
     19:             if (lastServiceDto == null) {
     20:                 // 获得所有的 Config Service 的地址
     21:                 List<ServiceDTO> configServices = getConfigServices();
     22:                 lastServiceDto = configServices.get(random.nextInt(configServices.size()));
     23:             }
     24:             // 组装长轮询通知变更的地址
     25:             url = assembleLongPollRefreshUrl(lastServiceDto.getHomepageUrl(), appId, cluster, dataCenter, m_notifications);
     26: 
     27:             logger.debug("Long polling from {}", url);
     28:             // 创建 HttpRequest 对象,并设置超时时间
     29:             HttpRequest request = new HttpRequest(url);
     30:             request.setReadTimeout(LONG_POLLING_READ_TIMEOUT);
     31: 
     32:             // 【TODO 6001】Tracer 日志
     33:             transaction.addData("Url", url);
     34: 
     35:             // 发起请求,返回 HttpResponse 对象
     36:             final HttpResponse<List<ApolloConfigNotification>> response = m_httpUtil.doGet(request, m_responseType);
     37:             logger.debug("Long polling response: {}, url: {}", response.getStatusCode(), url);
     38: 
     39:             // 有新的通知,刷新本地的缓存
     40:             if (response.getStatusCode() == 200 && response.getBody() != null) {
     41:                 // 更新 m_notifications
     42:                 updateNotifications(response.getBody());
     43:                 // 更新 m_remoteNotificationMessages
     44:                 updateRemoteNotifications(response.getBody());
     45:                 // 【TODO 6001】Tracer 日志
     46:                 transaction.addData("Result", response.getBody().toString());
     47:                 // 通知对应的 RemoteConfigRepository 们
     48:                 notify(lastServiceDto, response.getBody());
     49:             }
     50: 
     51:             // 无新的通知,重置连接的 Config Service 的地址,下次请求不同的 Config Service ,实现负载均衡。
     52:             // try to load balance
     53:             if (response.getStatusCode() == 304 && random.nextBoolean()) { // 随机
     54:                 lastServiceDto = null;
     55:             }
     56:             // 标记成功
     57:             m_longPollFailSchedulePolicyInSecond.success();
     58:             // 【TODO 6001】Tracer 日志
     59:             transaction.addData("StatusCode", response.getStatusCode());
     60:             transaction.setStatus(Transaction.SUCCESS);
     61:         } catch (Throwable ex) {
     62:             // 重置连接的 Config Service 的地址,下次请求不同的 Config Service
     63:             lastServiceDto = null;
     64:             // 【TODO 6001】Tracer 日志
     65:             Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
     66:             transaction.setStatus(ex);
     67:             // 标记失败,计算下一次延迟执行时间
     68:             long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail();
     69:             logger.warn("Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}",
     70:                     sleepTimeInSecond, appId, cluster, assembleNamespaces(), url, ExceptionUtil.getDetailMessage(ex));
     71:             // 等待一定时间,下次失败重试
     72:             try {
     73:                 TimeUnit.SECONDS.sleep(sleepTimeInSecond);
     74:             } catch (InterruptedException ie) {
     75:                 //ignore
     76:             }
     77:         } finally {
     78:             transaction.complete();
     79:         }
     80:     }
     81: }
    
    • 第 5 至 80 行:循环执行,直到停止或线程中断。

    • 第 7 至 13 行:调用 RateLimiter#tryAcquire(long timeout, TimeUnit unit) 方法,判断是否被限流。若限流,sleep 5 秒,避免对 Config Service 请求过于频繁。

    • 第 19 至 23 行:若无 lastServiceDto 对象,随机获得 Config Service 的地址。

    • 第 25 行:调用 #assembleLongPollRefreshUrl(...) 方法,组装长轮询通知变更的地址。

    • 第 29 至 30 行:创建 HttpRequest 对象,并设置超时时间。默认超时时间为 90 秒,大于 Config Service 的通知接口的 60 秒。

    • 第 36 行:调用 HttpUtil#doGet(request, Class) 方法,发起请求,返回 HttpResponse 对象。

    • 第 40 至 49 行:若返回状态码为 200 ,说明有新的通知,刷新本地的缓存。

      • 第 42 行:调用 #updateNotifications(List<ApolloConfigNotification>) 方法,更新 m_notifications 。详细解析,在 「3.7 updateNotifications」 。

      • 第 44 行:调用 #updateRemoteNotifications(List<ApolloConfigNotification>) 方法,更新 m_remoteNotificationMessages 。详细解析,在 「3.8 updateRemoteNotifications」 。

      • 第 48 行:调用 #notify(ServiceDTO, List<ApolloConfigNotification>) 方法,通知对应的 RemoteConfigRepository 们。详细解析,在 「3.9 notify」 。

    • 第 51 至 55 行:若返回状态码为 304 ,说明无新的通知,随机,重置连接的 Config Service 的地址,下次请求不同的 Config Service ,实现负载均衡。

    • 第 57 行:调用 SchedulePolicy#success() 方法,标记成功。

    • 第 61 至 76 行:处理异常。

      • 第 63 行:重置连接的 Config Service 的地址 lastServiceDto ,下次请求不同的 Config Service。

      • 第 67 至 70 行:调用 SchedulePolicy#fail() 方法,标记失败,计算下一次延迟执行时间。

      • 第 71 至 76 行:sleep,等待一定时间,下次失败重试。

    3.7 updateNotifications

    #updateNotifications(List<ApolloConfigNotification>) 方法,更新 m_notifications 。代码如下:

    private void updateNotifications(List<ApolloConfigNotification> deltaNotifications) {
        // 循环 ApolloConfigNotification
        for (ApolloConfigNotification notification : deltaNotifications) {
            if (Strings.isNullOrEmpty(notification.getNamespaceName())) {
                continue;
            }
            // 更新 m_notifications
            String namespaceName = notification.getNamespaceName();
            if (m_notifications.containsKey(namespaceName)) {
                m_notifications.put(namespaceName, notification.getNotificationId());
            }
            // 因为 .properties 在默认情况下被过滤掉,所以我们需要检查是否有 .properties 后缀的通知。如有,更新 m_notifications
            // since .properties are filtered out by default, so we need to check if there is notification with .properties suffix
            String namespaceNameWithPropertiesSuffix = String.format("%s.%s", namespaceName, ConfigFileFormat.Properties.getValue());
            if (m_notifications.containsKey(namespaceNameWithPropertiesSuffix)) {
                m_notifications.put(namespaceNameWithPropertiesSuffix, notification.getNotificationId());
            }
        }
    }
    

    3.8 updateRemoteNotifications

    #updateRemoteNotifications(List<ApolloConfigNotification>) 方法,更新 m_remoteNotificationMessages 。代码如下:

    private void updateRemoteNotifications(List<ApolloConfigNotification> deltaNotifications) {
        // 循环 ApolloConfigNotification
        for (ApolloConfigNotification notification : deltaNotifications) {
            if (Strings.isNullOrEmpty(notification.getNamespaceName())) {
                continue;
            }
            if (notification.getMessages() == null || notification.getMessages().isEmpty()) {
                continue;
            }
            // 若不存在 Namespace 对应的 ApolloNotificationMessages ,进行创建
            ApolloNotificationMessages localRemoteMessages = m_remoteNotificationMessages.get(notification.getNamespaceName());
            if (localRemoteMessages == null) {
                localRemoteMessages = new ApolloNotificationMessages();
                m_remoteNotificationMessages.put(notification.getNamespaceName(), localRemoteMessages);
            }
            // 合并通知消息到 ApolloNotificationMessages 中
            localRemoteMessages.mergeFrom(notification.getMessages());
        }
    }
    

    3.9 notify

    #notify(ServiceDTO, List<ApolloConfigNotification>) 方法,更新 m_remoteNotificationMessages 。代码如下:

    private void notify(ServiceDTO lastServiceDto, List<ApolloConfigNotification> notifications) {
        if (notifications == null || notifications.isEmpty()) {
            return;
        }
        // 循环 ApolloConfigNotification
        for (ApolloConfigNotification notification : notifications) {
            String namespaceName = notification.getNamespaceName(); // Namespace 的名字
            // 创建 RemoteConfigRepository 数组,避免并发问题
            // create a new list to avoid ConcurrentModificationException
            List<RemoteConfigRepository> toBeNotified = Lists.newArrayList(m_longPollNamespaces.get(namespaceName));
            // 因为 .properties 在默认情况下被过滤掉,所以我们需要检查是否有监听器。若有,添加到 RemoteConfigRepository 数组
            // since .properties are filtered out by default, so we need to check if there is any listener for it
            toBeNotified.addAll(m_longPollNamespaces.get(String.format("%s.%s", namespaceName, ConfigFileFormat.Properties.getValue())));
            // 获得远程的 ApolloNotificationMessages 对象,并克隆
            ApolloNotificationMessages originalMessages = m_remoteNotificationMessages.get(namespaceName);
            ApolloNotificationMessages remoteMessages = originalMessages == null ? null : originalMessages.clone();
            // 循环 RemoteConfigRepository ,进行通知
            for (RemoteConfigRepository remoteConfigRepository : toBeNotified) {
                try {
                    // 进行通知
                    remoteConfigRepository.onLongPollNotified(lastServiceDto, remoteMessages);
                } catch (Throwable ex) {
                    // 【TODO 6001】Tracer 日志
                    Tracer.logError(ex);
                }
            }
        }
    }
    

    4. SchedulePolicy

    com.ctrip.framework.apollo.core.schedule.SchedulePolicy ,定时策略接口。在 Apollo 中,用于执行失败,计算下一次执行的延迟时间。代码如下:

    public interface SchedulePolicy {
    
        /**
         * 执行失败
         *
         * @return 下次执行延迟
         */
        long fail();
    
        /**
         * 执行成功
         */
        void success();
    
    }
    

    4.1 ExponentialSchedulePolicy

    com.ctrip.framework.apollo.core.schedule.ExponentialSchedulePolicy ,实现 SchedulePolicy 接口,基于指数级计算的定时策略实现类。代码如下:

    public class ExponentialSchedulePolicy implements SchedulePolicy {
    
        /**
         * 延迟时间下限
         */
        private final long delayTimeLowerBound;
        /**
         * 延迟时间上限
         */
        private final long delayTimeUpperBound;
        /**
         * 最后延迟执行时间
         */
        private long lastDelayTime;
    
        public ExponentialSchedulePolicy(long delayTimeLowerBound, long delayTimeUpperBound) {
            this.delayTimeLowerBound = delayTimeLowerBound;
            this.delayTimeUpperBound = delayTimeUpperBound;
        }
    
        @Override
        public long fail() {
            long delayTime = lastDelayTime;
            // 设置初始时间
            if (delayTime == 0) {
                delayTime = delayTimeLowerBound;
            // 指数级计算,直到上限
            } else {
                delayTime = Math.min(lastDelayTime << 1, delayTimeUpperBound);
            }
            // 最后延迟执行时间
            lastDelayTime = delayTime;
            // 返回
            return delayTime;
        }
    
        @Override
        public void success() {
            lastDelayTime = 0;
        }
    
        public static void main(String[] args) {
            ExponentialSchedulePolicy policy = new ExponentialSchedulePolicy(1, 120);
            for (int i = 0; i < 10; i++) {
                System.out.println(policy.fail());
            }
        }
    
    }
    
    • 每次执行失败,调用 #fail() 方法,指数级计算新的延迟执行时间。

    • 举例如下:

      delayTimeLowerBound, delayTimeUpperBound= [1, 120] 执行 10 轮
      1 2 4 8 16 32 64 120 120 120
      delayTimeLowerBound, delayTimeUpperBound= [30, 120] 执行 10 轮
      30 60 120 120 120 120 120 120 120 120 120 120
      

    666. 彩蛋

    ???? 整个配置加载的流程完成!!!我的天!!!

    充实的周天。



    欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢:

    已在知识星球更新源码解析如下:

    最近更新《芋道 SpringBoot 2.X 入门》系列,已经 20 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。

    提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。

    获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

GraphQL与Apollo Client在React中的实战应用与原理剖析 GraphQL是一种声明式API查询语言,通过单次请求精准获取所需字段,解决REST接口冗余、碎片化等问题;其核心原理在于服务端暴露统一Schema,客户端按需构造查询AST并执行。Apollo Client作为最成熟的React集成方案,提供缓存归一化、类型安全、DevTools调试等工程级能力,显著提升中大型应用的数据获取可预测性与可维护性。它适用于微前端数据解耦、跨组件状态共享、实时订阅及服务端状态管理(Server State Management)等典型场景,尤其适合已存在大量REST接口、亟需渐 阅读详情

相关推荐

Apollo配置中心从入门到精通:架构、部署与动态配置实战

在微服务架构中,配置管理是保障系统稳定性和灵活性的关键技术。其核心原理是将原本分散在各个应用中的配置文件,集中到统一的服务端进行管理,实现配置的版本化、环境隔离与实时推送。这种模式的技术价值在于,它彻底改变了传统需要重启应用才能生效的配置更新方式,极大地提升了运维效率和故障响应速度。典型的应用场景包括动态调整业务参数、功能开关的灰度发布、多环境配置的统一管理等。本文以广泛应用的Apollo配置中心为例,深入剖析其核心架构与‘推拉结合’的更新机制,并详细演示如何从零搭建服务端、实现Spring Boot客户端

weixin_30425949的博客 398

apollo基于长轮询的配置更新源码

目录 前言 一、apollo客户端长轮询请求源码 二、服务端 1.服务端接收请求处理代码 2.配置更新发布相关逻辑 三、客户端更新配置 总结 前言 长轮询和传统轮询一样从服务器请求数据,但是,长轮询中服务器不会立即给客户端返回数据,如果没有数据,服务端会保持这个请求等待数据到来,或者超时报错,之后把数据返回给客户端。 一、apollo客户端长轮询请求源码 客户端的请求逻辑比较简单,就是发起了一个超时时间为90s的http请求,关于数据返回之后的配置更新逻辑在详细说明。 priva

qq_35219329的博客 1338

Apollo配置中心实战:解决分布式系统配置版本管理难题

配置管理是分布式系统和微服务架构中的基础技术概念,其核心原理在于实现应用配置的集中化管理和动态更新。在技术价值层面,良好的配置管理能够确保环境一致性、支持灰度发布和快速回滚,大幅提升系统稳定性。特别是在多环境部署场景下,配置版本混乱往往导致环境不一致和排查困难等实际问题。通过配置中心的层次化模型和版本控制机制,可以实现配置的隔离管理和变更追溯。本文基于Apollo配置中心,深入解析配置版本管理的核心痛点,提供从环境搭建、客户端集成到生产级最佳实践的完整解决方案,涵盖灰度发布、敏感配置加密等关键场景,帮助开发

weixin_33812433的博客 409

apollo-client源码分析

Apollo配置中心,JavaClient的源码解析

肥牛小窝 1957

Apollo配置中心:多环境与集群配置的架构设计与生产实践

在微服务架构中,配置管理是保障服务稳定与高效协作的核心基础设施。其核心原理在于将应用配置外部化、集中化管理,实现配置与代码的分离,从而提升部署灵活性和运维效率。这项技术的核心价值在于能够支撑应用在多环境(开发、测试、生产)下的差异化部署,并通过高可用架构避免单点故障,是保障业务连续性的关键。典型的应用场景包括数据库连接、功能开关、第三方服务地址等动态参数的统一管理。本文聚焦于业界广泛使用的Apollo配置中心,深入剖析其实现多环境隔离与**服务端集群**高可用的设计哲学。通过解析**Meta Server*

weixin_34163553的博客 408

codemirror6 制作markdown编辑器(源码模式)

总体上感觉能用,但是不怎么友好,官方文档有点散乱,而且关键字高亮功能是独立出去的,去官方文档找半天,也没找到怎么改。EditorView.theme可以往EditorView模块中修改CSS的样式,从而影响编辑器的样式展示。"### 测试\n\n```javascript\nlet x = 'y'\n```"这个插件中的markdown语法的高亮样式。//这里指定markdown中代码块使用的解析扩展。开头的class样式,并且还需要在选择器前面添加。//markdown语言解析扩展。

qq_43203949的博客 1784

apollo配置中心源码全解析

文章目录前言 前言 紧接前文nacos配置中心,本文继续讲目前比较火热的动态配置中心apollo,从源码层面分析一下它的实现 以apollo-client-1.9.2源码进行分析,关于如何使用apollo本文不再赘述,笔者是下载官方1.9.2的源码到本地启动项目的,至于如何启动可以看这篇文章 pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"

qq_31086797的博客 4587

智能车图像处理去畸变+逆透视教程

图像处理,去畸变与逆透视整合

wu58430的博客 1万+

熬夜之作:一文带你了解Cat分布式监控

如果需要使用 Spring Data Redis 的话,直接集成 kitty-spring-cloud-starter-redis 就可以,kitty-spring-cloud-starter-redis 中对 Redis 的命令进行了埋点,可以在 Cat 上直观的查看对应的命令和消耗的时间。CAT 很大的优势是它是一个实时系统,CAT 大部分系统是分钟级统计,但是从数据生成到服务端处理结束是秒级别,秒级定义是 48 分钟 40 秒,基本上看到 48 分钟 38 秒数据,整体报表的统计粒度是分钟级;

程序员高级码农的博客 2596

ThinkPad X230魔改指南:从博通网卡驱动到1080P屏显全攻略(附Sonoma避坑清单)

本文详细介绍了ThinkPad X230的全面改造方案,包括博通网卡驱动(BCM94352HMB)的安装与调试、1080P屏幕改装技术以及macOS Sonoma系统的适配优化。通过硬件升级和软件调优,使这台经典商务本焕发新生,适合DIY爱好者和技术极客参考实践。

weixin_30379531的博客 589

SAP CO模块实战:成本中心会计分割结构配置全流程(OKES事务码详解)

本文详细解析了SAP CO模块中成本中心会计分割结构的配置全流程,重点讲解了OKES事务码的实战操作。内容涵盖分割结构的概念理解、配置前的次级成本要素与作业类型主数据准备,并通过步骤拆解演示了如何定义分割结构、规则与版本,以及如何将配置关联到成本中心并执行分割。最后提供了常见问题排查与优化建议,旨在帮助顾问及财务人员掌握成本精确分摊的关键配置,确保期末成本核算的准确性。

embedding5hiker的博客 808

服务监控CAT的使用

文章目录什么是CATCAT报表介绍下载和发布服务 什么是CAT CAT是由大众点评开源的一款调用链监控系统,基于Java开发的。 优点:聚合报表丰富,中文支持好,国内案例多。 缺点:具有代码侵入性 CAT报表介绍 报表名称 报表内容 Transaction报表 一段代码的运行时间、次数、比如URL/cache/sql执行次数相应时间 Event报表 一段代码运行次数,比如出现一次异常 Problem报表 根据Transaction/Event数据分析出系统可能出现的一次慢程序 H

weixin_43790613的博客 5189

ArcGIS 10.8软件安装包免费下载及安装教程

ArcGIS 10.8安装教程

qq_44894692的博客 2万+

Apollo源码解析——Client轮询拉取配置

文章目录一、概述二.代码流程 一、概述 Client的轮询包括两部分: RemoteConfigRepository,定时轮询Config Service的/configs/{appId}/{clusterName}/{namespace} 接口的配置读取 RemoteConfigLongPollService 长轮询 Config Service的配置变更通知 /notification/v2接口 二.代码流程 1. AbstractConfigRepository#trySync方法 客户

ZXMSH的博客 731

光伏发电预测(LSTM、CNN_LSTM和XGBoost回归模型,Python代码)

一旦结果与预测差距较大,可能存在光伏系统的问题,需要找出原因,然后采取适当措施来修复光伏系统并做出更好的决策。例如,根据准确的预测,光伏系统运营商可以平衡电力消耗,并将多余的电力储备用于紧急情况。然而,光伏系统的发电量估算是一个挑战,因为光伏系统的发电量受到天气条件的极大影响。整个项目文件夹(第一个文件夹为xgboost模型相关的包文件,xg.py是xgboost模型英文注释版本,xg_chinese.py是xgboost模型中文注释版本)表示空气的温度,通常以摄氏度(°C)或华氏度(°F)为单位。

2301_79699110的博客 3034

IMX6ULL---从零开始移植uboot-imx

IMX6ULL---从零开始移植uboot-imx

weixin_42162924的博客 1029

Apollo核心源码解析(二):Apollo Client轮询配置(ConfigRepository与RemoteConfigLongPollService)、配置中心通用设计模型

本文接上文Apollo核心源码解析(一):Portal发布配置、Admin Service发送ReleaseMessage、Config Service通知客户端 3、Apollo Client 上图简要描述了Apollo客户端的实现原理: 客户端和服务端保持了一个长连接,从而能第一时间获得配置更新的推送(通过Http Long Polling实现) 客户端还会定时从Apollo配置中心服务端拉取应用的最新配置 这是一个fallback机制,为了防止推送机制失效导致配置不更新 客户端定时拉取会上报.

hxt的博客 2281

YOLOv8 改进:添加 LSK 注意力机制

通过添加 LSK 注意力机制,YOLOv8 能够更有效地捕捉特征图上的重要信息,提高检测性能,尤其是在复杂场景下展现出色的表现。这种方法不仅适用于资源受限的设备,还能在丰富多样的实际应用中提供强劲支持。

走向CTO的路上... 1223

Apollo源码-长轮询客户端实现

前言 在更新Spring Cloud Alibaba Nacos时,想到之前阅读过Apollo的源码,便在这插入记录了过来,后续更新Nacos Config源码 Apollo简介 fork 源码地址 apollo源码 参考apollo架构中心设计 主要分为 Config Service、Admin Service、Portal、Client 四部分 上文介绍到长轮询服务端实现,本文介绍客户端的长轮询实现 长轮询感知配置发布-客户端实现 从上文中我们知道,服务端暴露了一个将请求挂起60s的接口 /notifi

m0_37268363的博客 1093

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Apollo- 配置推送机制:长轮询与事件推送的实现原理与配置

请求路径必需 Query 参数appIdcluster推荐 Header(客户端声明最大等待时间)(全链路追踪 ID)成功响应(200)Body:Header:空响应(304)当超时且无变更时返回,客户端立即重试Apollo 官方文档 - 长轮询协议说明🔗 此链接为 Apollo 官网中文设计文档页,包含协议字段完整定义与状态码语义,长期有效。Apollo 的推送不是炫技的“黑科技”,而是一套以稳定性为底线、以兼容性为前提、以渐进式演进为核心不做假设。

千淘万漉虽辛苦,吹尽狂沙始到金 1万+

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

apollo源码(2)-client

1.概述 Client 通过轮询的方式,从 Config Service 读取配置。Client 的轮询包括两部分: 1.RemoteConfigRepository ,定时轮询 Config Service 的配置读取 2.RemoteConfigLongPollService ,长轮询 Config Service 的配置变更通知/notifications/v2接口 当有新的...

shandadadada的博客 660

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Learn Apollo 实战:用 dataIdFromObject 与 updateQueries 管理 Apollo Client 缓存

本篇文章基于 Learn Apollo 教程的《Managing Apollo store》扩展阅读(Excursion 02)编写,深入讲解 Apollo Client 在客户端缓存查询与变更(mutation)结果的默认机制、如何通过 `dataIdFromObject` 实现数据规范化(normalization),以及如何利用 `updateQueries` 与 `immutability

gitblog_01021的博客 387

使用 React、Apollo Client 与 Prisma 构建全栈 GraphQL 应用:React & Apollo Quickstart 实战指南

本指南基于 Prisma 官方文档《React & Apollo Quickstart》,完整演示如何用 React、GraphQL 与 Node.js 搭建一个全栈应用(一个简单的 Instagram 克隆):以 `graphql-yoga` 作为 GraphQL 服务器,通过 `prisma-binding` 将应用层 Schema 与 Prisma 数据库服务连接起来,前端使用 Apollo

gitblog_01052的博客 863

Agollo架构深度解析:从源码理解配置同步的核心原理

🚀 **Agollo** 是Go语言实现的Apollo配置中心客户端,提供了实时配置同步、灰度发布、容灾备份等核心功能。本文将深入剖析Agollo的架构设计,带你从源码层面理解配置同步的核心原理,掌握这个强大的配置管理工具的实现机制。 ## 📋 文章概览 Agollo作为Apollo配置中心的Go客户端,其架构设计体现了现代微服务配置管理的核心思想。通过本文,你将了解: - Agollo

gitblog_00616的博客 1005

【微服务架构组件之配置中心二】Apollo

配置中心

qq_35789269的博客 1054
上一篇: 关于数据中台的深度思考与总结,20000 字不到一丢丢。。。
下一篇: Apollo 源码解析 —— Config Service 记录 Instance
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值