Apollo 源码解析 —— Config Service 配置读取接口

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

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

管她前浪,还是后浪?

能浪的浪,才是好浪!

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

源码精品专栏

 

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

  • 1. 概述

  • 2. ConfigController

    • 2.1 构造方法

    • 2.2 queryConfig

    • 2.3 tryToGetClientIp

    • 2.4 mergeReleaseConfigurations

  • 3. ConfigService

    • 3.1 AbstractConfigService

    • 3.3 DefaultConfigService

    • 3.4 ConfigServiceWithCache

  • 4. ApolloConfig

  • 666. 彩蛋


1. 概述

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

本文接 《Apollo 源码解析 —— Config Service 通知配置变化》 一文,分享 Config Service 配置读取的接口的实现。在上文,我们看到通知变化接口,仅返回通知相关的信息,而不包括配置相关的信息。所以 Config Service 需要提供配置读取的接口。

???? 为什么不在通知变化的同时,返回最新的配置信息呢?老艿艿请教了作者,下一篇文章进行分享。

OK,让我们开始看看具体的代码实现。

2. ConfigController

com.ctrip.framework.apollo.configservice.controller.ConfigController ,配置 Controller ,仅提供 configs/{appId}/{clusterName}/{namespace:.+} 接口,提供配置读取的功能。

2.1 构造方法

private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults();

private static final Type configurationTypeReference = new TypeToken<Map<String, String>>() {}.getType();

@Autowired
private ConfigService configService;
@Autowired
private AppNamespaceServiceWithCache appNamespaceService;
@Autowired
private NamespaceUtil namespaceUtil;
@Autowired
private InstanceConfigAuditUtil instanceConfigAuditUtil;
@Autowired
private Gson gson

2.2 queryConfig

  1: @RequestMapping(value = "/{appId}/{clusterName}/{namespace:.+}", method = RequestMethod.GET)
  2: public ApolloConfig queryConfig(@PathVariable String appId, @PathVariable String clusterName,
  3:                                 @PathVariable String namespace,
  4:                                 @RequestParam(value = "dataCenter", required = false) String dataCenter,
  5:                                 @RequestParam(value = "releaseKey", defaultValue = "-1") String clientSideReleaseKey,
  6:                                 @RequestParam(value = "ip", required = false) String clientIp,
  7:                                 @RequestParam(value = "messages", required = false) String messagesAsString,
  8:                                 HttpServletRequest request, HttpServletResponse response) throws IOException {
  9:     String originalNamespace = namespace;
 10:     // 若 Namespace 名以 .properties 结尾,移除该结尾,并设置到 ApolloConfigNotification 中。例如 application.properties => application 。
 11:     // strip out .properties suffix
 12:     namespace = namespaceUtil.filterNamespaceName(namespace);
 13:     // 获得归一化的 Namespace 名字。因为,客户端 Namespace 会填写错大小写。
 14:     //fix the character case issue, such as FX.apollo <-> fx.apollo
 15:     namespace = namespaceUtil.normalizeNamespace(appId, namespace);
 16: 
 17:     // 若 clientIp 未提交,从 Request 中获取。
 18:     if (Strings.isNullOrEmpty(clientIp)) {
 19:         clientIp = tryToGetClientIp(request);
 20:     }
 21: 
 22:     // 解析 messagesAsString 参数,创建 ApolloNotificationMessages 对象。
 23:     ApolloNotificationMessages clientMessages = transformMessages(messagesAsString);
 24: 
 25:     // 创建 Release 数组
 26:     List<Release> releases = Lists.newLinkedList();
 27:     // 获得 Namespace 对应的 Release 对象
 28:     String appClusterNameLoaded = clusterName;
 29:     if (!ConfigConsts.NO_APPID_PLACEHOLDER.equalsIgnoreCase(appId)) {
 30:         // 获得 Release 对象
 31:         Release currentAppRelease = configService.loadConfig(appId, clientIp, appId, clusterName, namespace, dataCenter, clientMessages);
 32:         if (currentAppRelease != null) {
 33:             // 添加到 Release 数组中。
 34:             releases.add(currentAppRelease);
 35:             // 获得 Release 对应的 Cluster 名字
 36:             // we have cluster search process, so the cluster name might be overridden
 37:             appClusterNameLoaded = currentAppRelease.getClusterName();
 38:         }
 39:     }
 40:     // 若 Namespace 为关联类型,则获取关联的 Namespace 的 Release 对象
 41:     // if namespace does not belong to this appId, should check if there is a public configuration
 42:     if (!namespaceBelongsToAppId(appId, namespace)) {
 43:         // 获得 Release 对象
 44:         Release publicRelease = this.findPublicConfig(appId, clientIp, clusterName, namespace, dataCenter, clientMessages);
 45:         // 添加到 Release 数组中
 46:         if (!Objects.isNull(publicRelease)) {
 47:             releases.add(publicRelease);
 48:         }
 49:     }
 50:     // 若获得不到 Release ,返回状态码为 404 的响应
 51:     if (releases.isEmpty()) {
 52:         response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format("Could not load configurations with appId: %s, clusterName: %s, namespace: %s",
 53:                 appId, clusterName, originalNamespace));
 54:         Tracer.logEvent("Apollo.Config.NotFound", assembleKey(appId, clusterName, originalNamespace, dataCenter));
 55:         return null;
 56:     }
 57: 
 58:     // 记录 InstanceConfig
 59:     auditReleases(appId, clusterName, dataCenter, clientIp, releases);
 60: 
 61:     // 计算 Config Service 的合并 ReleaseKey
 62:     String mergedReleaseKey = releases.stream().map(Release::getReleaseKey).collect(Collectors.joining(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR));
 63:     // 对比 Client 的合并 Release Key 。若相等,说明没有改变,返回状态码为 302 的响应
 64:     if (mergedReleaseKey.equals(clientSideReleaseKey)) {
 65:         // Client side configuration is the same with server side, return 304
 66:         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
 67:         Tracer.logEvent("Apollo.Config.NotModified", assembleKey(appId, appClusterNameLoaded, originalNamespace, dataCenter));
 68:         return null;
 69:     }
 70: 
 71:     // 创建 ApolloConfig 对象
 72:     ApolloConfig apolloConfig = new ApolloConfig(appId, appClusterNameLoaded, originalNamespace, mergedReleaseKey);
 73:     // 合并 Release 的配置,并将结果设置到 ApolloConfig 中
 74:     apolloConfig.setConfigurations(mergeReleaseConfigurations(releases));
 75: 
 76:     // 【TODO 6001】Tracer 日志
 77:     Tracer.logEvent("Apollo.Config.Found", assembleKey(appId, appClusterNameLoaded, originalNamespace, dataCenter));
 78:     return apolloConfig;
 79: }
  • GET /configs/{appId}/{clusterName}/{namespace:.+} 接口,指定 Namespace 的配置读取。在 《Apollo 官方文档  —— 其它语言客户端接入指南 —— 1.3 通过不带缓存的Http接口从Apollo读取配置》 中,有该接口的接口定义说明。

  • clientSideReleaseKey 请求参数,客户端侧的 Release Key ,用于和获得的 Release 的 releaseKey 对比,判断是否有配置更新。

  • clientIp 请求参数,客户端 IP ,用于灰度发布的功能。???? 本文会跳过和灰度发布相关的内容,后续文章单独分享。

  • messagesAsString  请求参数,客户端当前请求的 Namespace 的通知消息明细,在【第 23 行】中,调用 #transformMessages(messagesAsString) 方法,解析 messagesAsString 参数,创建 ApolloNotificationMessages 对象。在  《Apollo 源码解析 —— Config Service 通知配置变化》 中,我们已经看到通知变更接口返回的就包括 ApolloNotificationMessages 对象。#transformMessages(messagesAsString) 方法,代码如下:

    ApolloNotificationMessages transformMessages(String messagesAsString) {
        ApolloNotificationMessages notificationMessages = null;
        if (!Strings.isNullOrEmpty(messagesAsString)) {
            try {
                notificationMessages = gson.fromJson(messagesAsString, ApolloNotificationMessages.class);
            } catch (Throwable ex) {
                Tracer.logError(ex);
            }
        }
        return notificationMessages;
    }
    
  • 第 12 行:调用 NamespaceUtil#filterNamespaceName(namespaceName) 方法,若 Namespace 名以 ".properties" 结尾,移除该结尾。

  • 第 15 行:调用 NamespaceUtil#normalizeNamespace(appId, originalNamespace) 方法,获得归一化的 Namespace 名字。因为,客户端 Namespace 会填写错大小写。

  • 第 17 至 20 行:若客户端未提交 clientIp ,调用 #tryToGetClientIp(HttpServletRequest) 方法,获取 IP 。详细解析,见 「2.3 tryToGetClientIp」 方法。

  • ========== 分割线 ==========

  • 第 26 行:创建 Release 数组。

  • 第 27 至 39 行:获得 Namespace 对应的最新的 Release 对象。

    • 第 31 行:调用 ConfigService#loadConfig(appId, clientIp, appId, clusterName, namespace, dataCenter, clientMessages) 方法,获得 Release 对象。详细解析,见 「3. ConfigService」 方法。

    • 第 34 行:添加到 Release 书中。

    • 第 37 行:获得 Release 对应的 Cluster 名字。因为,在 ConfigService#loadConfig(appId, clientIp, appId, clusterName, namespace, dataCenter, clientMessages) 方法中,会根据 clusterName 和 dataCenter 分别查询 Release 直到找到一个,所以需要根据结果的 Release 获取真正的 Cluster 名。

  • 第 40 至 49 行:若 Namespace 为关联类型,则获取关联的 Namespace 的最新的 Release 对象。

    • 在其内部,也是调用 ConfigService#loadConfig(appId, clientIp, appId, clusterName, namespace, dataCenter, clientMessages) 方法,获得 Namespace 最新的 Release 对象。

    • x

    • 第 42 行:调用 #namespaceBelongsToAppId(appId, namespace)  方法,判断 Namespace 非当前 App 下的,这是关联类型的前提。代码如下:

      private boolean namespaceBelongsToAppId(String appId, String namespaceName) {
          // Namespace 非 'application' ,因为每个 App 都有
          // Every app has an 'application' namespace
          if (Objects.equals(ConfigConsts.NAMESPACE_APPLICATION, namespaceName)) {
              return true;
          }
          // App 编号非空
          // if no appId is present, then no other namespace belongs to it
          if (ConfigConsts.NO_APPID_PLACEHOLDER.equalsIgnoreCase(appId)) {
              return false;
          }
          // 非当前 App 下的 Namespace
          AppNamespace appNamespace = appNamespaceService.findByAppIdAndNamespace(appId, namespaceName);
          return appNamespace != null;
      }
      
    • 第 44 行:调用 #findPublicConfig(...) 方法,获得公用类型的 Namespace 的 Release 对象。代码如下:

      private Release findPublicConfig(String clientAppId, String clientIp, String clusterName,
                                       String namespace, String dataCenter, ApolloNotificationMessages clientMessages) {
          // 获得公用类型的 AppNamespace 对象
          AppNamespace appNamespace = appNamespaceService.findPublicNamespaceByName(namespace);
          // 判断非当前 App 下的,那么就是关联类型。
          // check whether the namespace's appId equals to current one
          if (Objects.isNull(appNamespace) || Objects.equals(clientAppId, appNamespace.getAppId())) {
              return null;
          }
          String publicConfigAppId = appNamespace.getAppId();
          // 获得 Namespace 最新的 Release 对象
          return configService.loadConfig(clientAppId, clientIp, publicConfigAppId, clusterName, namespace, dataCenter, clientMessages);
      }
      
    • 第 45 至 48 行:添加到 Release 数组中。

  • 第 50 至 56 行:若获得不到 Release ,返回状态码为 404 的响应。

  • ========== 分割线 ==========

  • 第 59 行:调用 #auditReleases(...) 方法,记录 InstanceConfig 。详细解析,见 《Apollo 源码解析 —— Config Service 记录 Instance》 。

  • ========== 分割线 ==========

  • 第 62 行:计算 Config Service 的合并 ReleaseKey 。当有多个 Release 时,使用 "+" 作为字符串的分隔。

  • 第 64 至 69 行:对比 Client 的合并 Release Key 。若相等,说明配置没有改变,返回状态码为 302 的响应。

  • ========== 分割线 ==========

  • 第 72 行:创建 ApolloConfig 对象。详细解析,见 「3. ApolloConfig」 方法。

  • 第 74 行:调用 #mergeReleaseConfigurations(List<Release) 方法,合并多个 Release 的配置集合,并将结果设置到 ApolloConfig 中。详细解析,见 「2.4  mergeReleaseConfigurations」 方法。

  • 第 77 行:【TODO 6001】Tracer 日志

  • 第 78 行:返回 ApolloConfig 对象。

2.3 tryToGetClientIp

#tryToGetClientIp(HttpServletRequest) 方法,从请求中获取 IP 。代码如下:

private String tryToGetClientIp(HttpServletRequest request) {
    String forwardedFor = request.getHeader("X-FORWARDED-FOR");
    if (!Strings.isNullOrEmpty(forwardedFor)) {
        return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
    }
    return request.getRemoteAddr();
}
  • 关于 "X-FORWARDED-FOR" Header ,详细解析见 《HTTP 请求头中的 X-Forwarded-For》 。

2.4 mergeReleaseConfigurations

#mergeReleaseConfigurations(List<Release) 方法,合并多个 Release 的配置集合。代码如下:

Map<String, String> mergeReleaseConfigurations(List<Release> releases) {
    Map<String, String> result = Maps.newHashMap();
    // 反转 Release 数组,循环添加到 Map 中。
    for (Release release : Lists.reverse(releases)) {
        result.putAll(gson.fromJson(release.getConfigurations(), configurationTypeReference));
    }
    return result;
}
  • 为什么要反转数组?因为关联类型的 Release 后添加到 Release 数组中。但是,App 下 的 Release 的优先级更高,所以进行反转。

3. ConfigService

com.ctrip.framework.apollo.configservice.service.config.ConfigService ,实现 ReleaseMessageListener 接口,配置 Service 接口。代码如下:

public interface ConfigService extends ReleaseMessageListener {

    /**
     * Load config
     *
     * 读取指定 Namespace 的最新的 Release 对象
     *
     * @param clientAppId       the client's app id
     * @param clientIp          the client ip
     * @param configAppId       the requested config's app id
     * @param configClusterName the requested config's cluster name
     *                          Cluster 的名字
     * @param configNamespace   the requested config's namespace name
     * @param dataCenter        the client data center
     *                          数据中心的 Cluster 的名字
     * @param clientMessages    the messages received in client side
     * @return the Release
     */
    Release loadConfig(String clientAppId, String clientIp, String configAppId, String
            configClusterName, String configNamespace, String dataCenter, ApolloNotificationMessages clientMessages);

}

子类如下图所示:

最终有两个子类,差异点在于是否使用缓存,通过 ServerConfig "config-service.cache.enabled" 配置,默认关闭。开启后能提高性能,但是会增大内存消耗!

在 ConfigServiceAutoConfiguration 中,初始化使用的 ConfigService 实现类,代码如下:

@Autowired
private BizConfig bizConfig;

@Bean
public ConfigService configService() {
    // 开启缓存,使用 ConfigServiceWithCache
    if (bizConfig.isConfigServiceCacheEnabled()) {
        return new ConfigServiceWithCache();
    }
    // 不开启缓存,使用 DefaultConfigService
    return new DefaultConfigService();
}

3.1 AbstractConfigService

com.ctrip.framework.apollo.configservice.service.config.AbstractConfigService ,实现 ConfigService 接口,配置 Service 抽象类,实现公用的获取配置的逻辑,并暴露抽象方法,让子类实现。抽象方法如下:

/**
 * 获得指定编号,并且有效的 Release 对象
 *
 * Find active release by id
 *
 * @param id Release 编号
 */
protected abstract Release findActiveOne(long id, ApolloNotificationMessages clientMessages);

/**
 * 获得最新的,并且有效的 Release 对象
 *
 * Find active release by app id, cluster name and namespace name
 */
protected abstract Release findLatestActiveRelease(String configAppId, String configClusterName,
                                                   String configNamespaceName, ApolloNotificationMessages clientMessages);

3.1.1 loadConfig

#loadConfig(...) 实现方法,代码如下:

  1: @Override
  2: public Release loadConfig(String clientAppId, String clientIp, String configAppId, String configClusterName,
  3:                           String configNamespace, String dataCenter, ApolloNotificationMessages clientMessages) {
  4:     // 优先,获得指定 Cluster 的 Release 。若存在,直接返回。
  5:     // load from specified cluster fist
  6:     if (!Objects.equals(ConfigConsts.CLUSTER_NAME_DEFAULT, configClusterName)) {
  7:         Release clusterRelease = findRelease(clientAppId, clientIp, configAppId, configClusterName, configNamespace,
  8:                 clientMessages);
  9:         if (!Objects.isNull(clusterRelease)) {
 10:             return clusterRelease;
 11:         }
 12:     }
 13: 
 14:     // 其次,获得所属 IDC 的 Cluster 的 Release 。若存在,直接返回
 15:     // try to load via data center
 16:     if (!Strings.isNullOrEmpty(dataCenter) && !Objects.equals(dataCenter, configClusterName)) {
 17:         Release dataCenterRelease = findRelease(clientAppId, clientIp, configAppId, dataCenter, configNamespace, clientMessages);
 18:         if (!Objects.isNull(dataCenterRelease)) {
 19:             return dataCenterRelease;
 20:         }
 21:     }
 22: 
 23:     // 最后,获得默认 Cluster 的 Release 。
 24:     // fallback to default release
 25:     return findRelease(clientAppId, clientIp, configAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, configNamespace, clientMessages);
 26: }
  • 第 4 至 12 行:优先,获得指定 Cluster 的 Release 。若存在,直接返回。

  • 第 14 至 21 行:其次,获得所属 IDC 的 Cluster 的 Release 。若存在,直接返回。

  • 第 25 行:最后,获得默认的 Cluster 的 Release 。

  • 每一次获取,都调用了 #findRelease(...) 方法,获取对应的 Release 对象。详细解析,见 「3.2 findRelease」 方法。

  • 关于多 Cluster 的读取顺序,可参见 《Apollo 配置中心介绍 —— 4.4.1 应用自身配置的获取规则》 。这块的代码,就是实现该顺序,如下图:

3.1.2 findRelease

  1: /**
  2:  * Find release
  3:  *
  4:  * 获得 Release 对象
  5:  *
  6:  * @param clientAppId       the client's app id
  7:  * @param clientIp          the client ip
  8:  * @param configAppId       the requested config's app id
  9:  * @param configClusterName the requested config's cluster name
 10:  * @param configNamespace   the requested config's namespace name
 11:  * @param clientMessages    the messages received in client side
 12:  * @return the release
 13:  */
 14: private Release findRelease(String clientAppId, String clientIp, String configAppId, String configClusterName,
 15:                             String configNamespace, ApolloNotificationMessages clientMessages) {
 16:     // 读取灰度发布编号
 17:     Long grayReleaseId = grayReleaseRulesHolder.findReleaseIdFromGrayReleaseRule(clientAppId, clientIp, configAppId, configClusterName, configNamespace);
 18:     //  读取灰度 Release 对象
 19:     Release release = null;
 20:     if (grayReleaseId != null) {
 21:         release = findActiveOne(grayReleaseId, clientMessages);
 22:     }
 23:     // 非灰度,获得最新的,并且有效的 Release 对象
 24:     if (release == null) {
 25:         release = findLatestActiveRelease(configAppId, configClusterName, configNamespace, clientMessages);
 26:     }
 27:     return release;
 28: }
  • 第 17 行:调用 GrayReleaseRulesHolder#findReleaseIdFromGrayReleaseRule(...) 方法,读取灰度发布编号,即 GrayReleaseRule.releaseId 属性。详细解析,在 《Apollo 源码解析 —— Portal 灰度发布》 中。

  • 第 18 至 22 行:调用 #findActiveOne(grayReleaseId, clientMessages) 方法,读取灰度 Release 对象。

  • 第 23 至 26 行:若非灰度,调用 #findLatestActiveRelease(configAppId, configClusterName, configNamespace, clientMessages) 方法,获得最新的,并且有效的 Release 对象。

3.3 DefaultConfigService

com.ctrip.framework.apollo.configservice.service.config.DefaultConfigService ,实现 AbstractConfigService 抽象类,配置 Service 默认实现类,直接查询数据库,而不使用缓存。代码如下:

public class DefaultConfigService extends AbstractConfigService {

    @Autowired
    private ReleaseService releaseService;

    @Override
    protected Release findActiveOne(long id, ApolloNotificationMessages clientMessages) {
        return releaseService.findActiveOne(id);
    }

    @Override
    protected Release findLatestActiveRelease(String configAppId, String configClusterName, String configNamespace,
                                              ApolloNotificationMessages clientMessages) {
        return releaseService.findLatestActiveRelease(configAppId, configClusterName, configNamespace);
    }

    @Override
    public void handleMessage(ReleaseMessage message, String channel) {
        // since there is no cache, so do nothing
    }

}
  • ReleaseService ,在 《Apollo 源码解析 —— Portal 发布配置》 中,有详细解析。

3.4 ConfigServiceWithCache

com.ctrip.framework.apollo.configservice.service.config.ConfigServiceWithCache ,实现 AbstractConfigService 抽象类,基于 Guava Cache 的配置 Service 实现类。

3.4.1 构造方法

private static final Logger logger = LoggerFactory.getLogger(ConfigServiceWithCache.class);

/**
 * 默认缓存过滤时间,单位:分钟
 */
private static final long DEFAULT_EXPIRED_AFTER_ACCESS_IN_MINUTES = 60; //1 hour

// TRACER 日志内存的枚举
private static final String TRACER_EVENT_CACHE_INVALIDATE = "ConfigCache.Invalidate";
private static final String TRACER_EVENT_CACHE_LOAD = "ConfigCache.LoadFromDB";
private static final String TRACER_EVENT_CACHE_LOAD_ID = "ConfigCache.LoadFromDBById";
private static final String TRACER_EVENT_CACHE_GET = "ConfigCache.Get";
private static final String TRACER_EVENT_CACHE_GET_ID = "ConfigCache.GetById";

private static final Splitter STRING_SPLITTER = Splitter.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).omitEmptyStrings();

@Autowired
private ReleaseService releaseService;
@Autowired
private ReleaseMessageService releaseMessageService;
/**
 * ConfigCacheEntry 缓存
 *
 * KEY:Watch Key {@link ReleaseMessage#message}
 */
private LoadingCache<String, ConfigCacheEntry> configCache;
/**
 * Release 缓存
 *
 * KEY :Release 编号
 */
private LoadingCache<Long, Optional<Release>> configIdCache;
/**
 * 无 ConfigCacheEntry 占位对象
 */
private ConfigCacheEntry nullConfigCacheEntry;

public ConfigServiceWithCache() {
    nullConfigCacheEntry = new ConfigCacheEntry(ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, null);
}

3.4.2 ConfigCacheEntry

ConfigCacheEntry ,ConfigServiceWithCache 的内部私有静态类,配置缓存 Entry 。代码如下:

private static class ConfigCacheEntry {

    /**
     * 通知编号
     */
    private final long notificationId;
    /**
     * Release 对象
     */
    private final Release release;

    public ConfigCacheEntry(long notificationId, Release release) {
        this.notificationId = notificationId;
        this.release = release;
    }

    public long getNotificationId() {
        return notificationId;
    }

    public Release getRelease() {
        return release;
    }

}

3.4.3 初始化

#initialize() 方法,通过 Spring 调用,初始化缓存对象。代码如下:

  1: @PostConstruct
  2: void initialize() {
  3:     // 初始化 configCache
  4:     configCache = CacheBuilder.newBuilder()
  5:             .expireAfterAccess(DEFAULT_EXPIRED_AFTER_ACCESS_IN_MINUTES, TimeUnit.MINUTES) // 访问过期
  6:             .build(new CacheLoader<String, ConfigCacheEntry>() {
  7:                 @Override
  8:                 public ConfigCacheEntry load(String key) {
  9:                     // 格式不正确,返回 nullConfigCacheEntry
 10:                     List<String> namespaceInfo = STRING_SPLITTER.splitToList(key);
 11:                     if (namespaceInfo.size() != 3) {
 12:                         Tracer.logError(new IllegalArgumentException(String.format("Invalid cache load key %s", key)));
 13:                         return nullConfigCacheEntry;
 14:                     }
 15:                     // 【TODO 6001】Tracer 日志
 16:                     Transaction transaction = Tracer.newTransaction(TRACER_EVENT_CACHE_LOAD, key);
 17:                     try {
 18:                         // 获得最新的 ReleaseMessage 对象
 19:                         ReleaseMessage latestReleaseMessage = releaseMessageService.findLatestReleaseMessageForMessages(Lists.newArrayList(key));
 20:                         // 获得最新的,并且有效的 Release 对象
 21:                         Release latestRelease = releaseService.findLatestActiveRelease(namespaceInfo.get(0), namespaceInfo.get(1), namespaceInfo.get(2));
 22:                         // 【TODO 6001】Tracer 日志
 23:                         transaction.setStatus(Transaction.SUCCESS);
 24:                         // 获得通知编号
 25:                         long notificationId = latestReleaseMessage == null ? ConfigConsts.NOTIFICATION_ID_PLACEHOLDER : latestReleaseMessage.getId();
 26:                         // 若 latestReleaseMessage 和 latestRelease 都为空,返回 nullConfigCacheEntry
 27:                         if (notificationId == ConfigConsts.NOTIFICATION_ID_PLACEHOLDER && latestRelease == null) {
 28:                             return nullConfigCacheEntry;
 29:                         }
 30:                         // 创建 ConfigCacheEntry 对象
 31:                         return new ConfigCacheEntry(notificationId, latestRelease);
 32:                     } catch (Throwable ex) {
 33:                         // 【TODO 6001】Tracer 日志
 34:                         transaction.setStatus(ex);
 35:                         throw ex;
 36:                     } finally {
 37:                         // 【TODO 6001】Tracer 日志
 38:                         transaction.complete();
 39:                     }
 40:                 }
 41:             });
 42:     // 初始化 configIdCache
 43:     configIdCache = CacheBuilder.newBuilder()
 44:             .expireAfterAccess(DEFAULT_EXPIRED_AFTER_ACCESS_IN_MINUTES, TimeUnit.MINUTES) // 访问过期
 45:             .build(new CacheLoader<Long, Optional<Release>>() {
 46:                 @Override
 47:                 public Optional<Release> load(Long key) {
 48:                     // 【TODO 6001】Tracer 日志
 49:                     Transaction transaction = Tracer.newTransaction(TRACER_EVENT_CACHE_LOAD_ID, String.valueOf(key));
 50:                     try {
 51:                         // 获得 Release 对象
 52:                         Release release = releaseService.findActiveOne(key);
 53:                         // 【TODO 6001】Tracer 日志
 54:                         transaction.setStatus(Transaction.SUCCESS);
 55:                         // 使用 Optional 包装 Release 对象返回
 56:                         return Optional.ofNullable(release);
 57:                     } catch (Throwable ex) {
 58:                         // 【TODO 6001】Tracer 日志
 59:                         transaction.setStatus(ex);
 60:                         throw ex;
 61:                     } finally {
 62:                         // 【TODO 6001】Tracer 日志
 63:                         transaction.complete();
 64:                     }
 65:                 }
 66:             });
 67: }
  • 第 4 至 41 行:初始化 configCache 。

    • 第 9 至 14 行:key 格式不正确,返回 nullConfigCacheEntry 。

    • 第 19 行:调用 releaseMessageService.findLatestReleaseMessageForMessages(List<String>) 方法,获得最新的 ReleaseMessage 对象。这一步是 DefaultConfigService 没有的操作,用于读取缓存的时候,判断缓存是否过期,下文详细解析。

    • 第 21 行:调用 ReleaseService.findLatestActiveRelease(appId, clusterName, namespaceName) 方法,获得最新的,且有效的 Release 对象。

    • 第 25 行:获得通知编号。

    • 第 26 至 29 行:若 latestReleaseMessage 和 latestRelease 都为空,返回 nullConfigCacheEntry 。

    • 第 31 行:创建 ConfigCacheEntry 对象,并返回。

  • 第 42 至 66 行:初始化 configIdCache 。

    • 第 52 行:调用 ReleaseService#findActiveOne(key)  方法,获得 Release 对象。

    • 第 56 行:调用 Optional.ofNullable(Object) 方法,使用 Optional 包装 Release 对象,并返回。

3.4.4 handleMessage

  1: @Override
  2: public void handleMessage(ReleaseMessage message, String channel) {
  3:     logger.info("message received - channel: {}, message: {}", channel, message);
  4:     // 仅处理 APOLLO_RELEASE_TOPIC
  5:     if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(message.getMessage())) {
  6:         return;
  7:     }
  8:     try {
  9:         // 清空对应的缓存
 10:         invalidate(message.getMessage());
 11:         // 预热缓存,读取 ConfigCacheEntry 对象,重新从 DB 中加载。
 12:         // warm up the cache
 13:         configCache.getUnchecked(message.getMessage());
 14:     } catch (Throwable ex) {
 15:         //ignore
 16:     }
 17: }
  • 第 4 至 7 行:仅处理 APOLLO_RELEASE_TOPIC 。

  • 第 10 行:调用 #invalidate(message) 方法,清空对应的缓存。代码如下:

    private void invalidate(String key) {
        // 清空对应的缓存
        configCache.invalidate(key);
        // 【TODO 6001】Tracer 日志
        Tracer.logEvent(TRACER_EVENT_CACHE_INVALIDATE, key);
    }
    
  • 第 13 行:调用 LoadingCache#getUnchecked(key) 方法,预热缓存,读取 ConfigCacheEntry 对象,重新从 DB 中加载。

3.4.5 findLatestActiveRelease

  1: @Override
  2: protected Release findLatestActiveRelease(String appId, String clusterName, String namespaceName, ApolloNotificationMessages clientMessages) {
  3:     // 根据 appId + clusterName + namespaceName ,获得 ReleaseMessage 的 `message` 。
  4:     String key = ReleaseMessageKeyGenerator.generate(appId, clusterName, namespaceName);
  5:     // 【TODO 6001】Tracer 日志
  6:     Tracer.logEvent(TRACER_EVENT_CACHE_GET, key);
  7:     // 从缓存 configCache 中,读取 ConfigCacheEntry 对象
  8:     ConfigCacheEntry cacheEntry = configCache.getUnchecked(key);
  9:     // 若客户端的通知编号更大,说明缓存已经过期。
 10:     // cache is out-dated
 11:     if (clientMessages != null && clientMessages.has(key) && clientMessages.get(key) > cacheEntry.getNotificationId()) {
 12:         // 清空对应的缓存
 13:         // invalidate the cache and try to load from db again
 14:         invalidate(key);
 15:         // 读取 ConfigCacheEntry 对象,重新从 DB 中加载。
 16:         cacheEntry = configCache.getUnchecked(key);
 17:     }
 18:     // 返回 Release 对象
 19:     return cacheEntry.getRelease();
 20: }
  • 第 4 行:调用 ReleaseMessageKeyGenerator#generate(appId, clusterName, namespaceName) 方法,根据 appId + clusterName + namespaceName ,获得 ReleaseMessage 的 message 。

  • 第 8 行:调用 LoadingCache#getUnchecked(key) 方法,从缓存 configCache 中,读取 ConfigCacheEntry 对象。

  • 第 9 至 17 行:若客户端的通知编号更大,说明缓存已经过期。因为 #handleMessage(ReleaseMessage message, String channel) 方法,是通过定时扫描 ReleaseMessage 的机制实现,那么延迟是不可避免会存在的。所以通过此处比较的方式,实现缓存的过期的检查。

    • 第 14 行:调用 #invalidate(message) 方法,清空对应的缓存。

    • 第 16 行:调用 LoadingCache#getUnchecked(key) 方法,读取 ConfigCacheEntry 对象,重新从 DB 中加载。

  • 第 19 行:返回 Release 对象。

3.4.6 findActiveOne

@Override
protected Release findActiveOne(long id, ApolloNotificationMessages clientMessages) {
    // 【TODO 6001】Tracer 日志
    Tracer.logEvent(TRACER_EVENT_CACHE_GET_ID, String.valueOf(id));
    // 从缓存 configIdCache 中,读取 Release 对象
    return configIdCache.getUnchecked(id).orElse(null);
}

4. ApolloConfig

com.ctrip.framework.apollo.core.dto.ApolloConfig ,Apollo 配置 DTO 。代码如下:

public class ApolloConfig {

    /**
     * App 编号
     */
    private String appId;
    /**
     * Cluster 名字
     */
    private String cluster;
    /**
     * Namespace 名字
     */
    private String namespaceName;
    /**
     * 配置 Map
     */
    private Map<String, String> configurations;
    /**
     * Release Key
     *
     * 如果 {@link #configurations} 是多个 Release ,那 Release Key 是多个 `Release.releaseKey` 拼接,使用 '+' 拼接。
     */
    private String releaseKey;

}
  • 该类在 apollo-core 项目中,被 apollo-configservice 和 apollo-client 共同引用。因此,Apollo 的客户端,也使用 ApolloConfig 。

666. 彩蛋

???? 对流程上的细节,越来越清晰。

充实的周六。



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

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

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

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

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

Apollo总体设计&原理浅析 主要从 3 方面讲解:资源创建(App、Cluster、Namespace、Item)、配置发布、Client 配置同步。Apollo Client 同步配置主要依赖 ConfigRepository 接口。Config Service 在 Client 同步最新配置过程中主要职责有。上图描述了创建一个 namespace2 的灰度版本后,实体间的关系。RemoteConfigRepository 在构造方法中,小节从此拷贝)可知 Client 获取配置有两种方式。 阅读详情

相关推荐

Spring Boot集成Apollo配置中心:从零搭建到生产实践

在微服务架构中,配置管理是保障系统稳定性和可维护性的核心技术。传统的配置文件方式存在配置分散、动态更新困难、环境隔离风险高等问题。配置中心通过统一管理、实时推送和权限控制等机制,实现了配置的集中化与动态化,显著提升了运维效率和系统可靠性。其技术价值在于支持灰度发布、版本回滚和客户端高可用,广泛应用于互联网企业的微服务治理场景。本文聚焦于携程开源的Apollo配置中心,详细介绍了其核心概念、本地快速搭建方法,并提供了Spring Boot项目集成的完整实战指南,涵盖从环境准备到生产环境最佳实践的全过程,帮助开

weixin_33827590的博客 469

Apollo源码解析——ConfigService配置读取接口(客户端定时拉取接口)

文章目录一、概述二、代码流程 一、概述 上文讲了客户端定时轮询的接口,这里我们看下Config Service配置读取的接口的实现。 二、代码流程 1. ConfigController#queryConfig方法 代码很长,但是大体流程就是根据客户端的参数从服务端查询出来最新的配置,然后根据clientSideReleaseKey和服务端的ReleaseKey进行比较,判断配置有没有更新,这里重点看下loadConfig方法,怎么加载最新的配置 @GetMapping(value = "/{

ZXMSH的博客 1701

携程Apollo配置管理系统使用

Apollo是携程开源的分布式配置管理中心,支持多环境、多集群配置管理,具有实时推送、灰度发布、权限审计等特性。系统包含Portal(管理界面)、Config/Admin Service(配置服务)、Eureka(服务注册)和Client(客户端)四大模块。部署时需创建PortalDB和ConfigDB数据库,配置不同环境的数据源和端口。本文详细介绍了双节点部署方案,包括数据库配置、服务端口修改等步骤,适用于微服务架构下的配置管理需求。通过Apollo可以实现配置的集中化管理、动态更新和高可用性。

坚持做正确的事情! 1201

apollo配置中心部署到使用的心得总结

apollo配置中心架构剖析架构图 四个核心模块及其主要功能1. ConfigService 提供配置获取接口提供配置推送接口服务于Apollo客户端 2.AdminService提供配置管理接口提供配置修改发布接口服务于管理界面Portal 3.Client为应用获取配置,支持实时更新通过MetaServer获取ConfigService的服务列表使用客户端软负载SLB方式调用ConfigSer...

小小的幸福 5万+

apollo-configservice_apollo-configdev.log

apollo-configservice_apollo-configdev.log a sdasdasda

从配置文件加载顺序揭秘:为什么你的logback.xml读不到application.yml?

本文深入解析了Spring Boot中logback.xml无法读取application.yml配置的原因,揭示了Spring Boot配置加载机制与日志系统初始化的时序问题。通过对比logback.xml与logback-spring.xml的差异,提供了使用springProperty标签和系统属性传递等解决方案,帮助开发者有效解决日志配置问题。

weixin_29214335的博客 365

apollo配置中心之-如何启动源码及Config Service 通知配置变化源码解析

一、apollo整体架构 apollo服务端大概有3个服务: Config Service提供配置的读取、推送等功能,服务对象是Apollo客户端 Admin Service提供配置的修改、发布等功能,服务对象是Apollo Portal(管理界面) Config Service和Admin Service都是多实例、无状态部署,所以需要将自己注册到Eureka中并保持心跳 在Eureka之上我们架了一层Meta Server用于封装Eureka的服务发现接口 Client通过域名访问Meta Serv

lh87270202的博客 3682

MaxDEA如何计算超效率DEA

MaxDEA如何计算超效率DEA第一步,导入数据,设置输出和输出,点击OK;第二步,运行模型; 本文计算的是超效率DEA-BCC。 第一步,导入数据,设置输出和输出,点击OK; 第二步,运行模型; 在distance选项框中选择Radial:CCR(1978);BCC(1984)。 在Orientation中选择Non-oriented。其中,Input-oriented是投入最小;Outp...

王樰沫 1万+

Apollo通过注解获取配置的几种方式

在spring boot项目中读取apollo配置常用的方式一般有以下几种

jueMingc的博客 5160

别再为模糊的3D重建头疼了!手把手教你用3DSlicer处理DICOM数据,搞定医学影像三维可视化

本文详细解析了医学影像三维重建中常见的模糊问题,并手把手教你使用3DSlicer处理DICOM数据,实现精准的三维可视化。从层厚设置到数据格式转换,再到重建算法选择和渲染参数微调,提供了一套完整的优化方案,特别适合临床医生和医学影像处理人员提升工作效率。

weixin_28693447的博客 251

雷达信号处理DDC数字下变频

由于接收到的雷达信号频率较高,不能对其进行直接采样并数据处理,所以需要对雷达信号进行预处理,在降低其采样率的同时,将其由中频降低到低频,然后对输出的基带信号进行后续的解析,以便于获取雷达信号的特征参数。 本文采用数字正交下变频,将单通道信号转化为正交双通道信号,数字下变频(DDC)的原型为模拟下变频,通过对窄带雷达信号或单频信号进行数字混频,然后对信号进行正交采样,提取 I、Q 两路正交分量,最后通过滤波去除信号中的高频分量,将信号由中高频搬移至低频。 模拟下变频的系统框图如下: 其数学推导.

qq_44033461的博客 5236

Apollo配置中心Config Service的配置读取接口源码

Apollo ConfigService的核心机制分析:采用多级缓存(本地+Redis)提升配置读取性能,通过长轮询实现配置变更实时通知。关键设计包括分层缓存策略(基于appId/cluster/namespace的三元组)、数据库查询优化(索引加速)、异步处理机制及完善的容错降级方案。其架构体现了高性能与高可用平衡,在保证实时性的同时有效降低服务端压力,支持集群化部署和水平扩展能力。

油墨香^-^的博客 1061

PHP实战:5分钟搞定SM4国密加密算法集成(附完整代码)

本文详细介绍了如何在PHP项目中快速集成SM4国密加密算法,提供完整的代码实现和实际应用示例。从算法原理到核心代码解析,再到性能优化与安全实践,帮助开发者高效实现数据加密功能,满足金融、政务等领域的合规需求。

weixin_29315569的博客 356

Apollo核心源码解析(一):Portal发布配置、Admin Service发送ReleaseMessage、Config Service通知客户端

1、Apollo架构设计 Config Service提供配置的读取、推送等功能,服务对象是Apollo客户端 Admin Service提供配置的修改、发布等功能,服务对象是Apollo Portal(管理界面) Config Service和Admin Service都是多实例、无状态部署,所以需要将自己注册到Eureka中并保持心跳 在Eureka之上我们架了一层Meta Server用于封装Eureka的服务发现接口 Client通过域名访问Meta Server获取Config Service

hxt的博客 2191

【YOLOv8改进-注意力机制】LSKNet(Large Selective Kernel Network ):空间选择注意力

【YOLOv8改进-注意力机制】LSKNet(Large Selective Kernel Network ):空间选择注意力 (论文笔记+引入代码)。LSKNet能够动态调整其大的空间接收场,以更好地模拟遥感场景中各种对象的范围上下文。据我们所知,这是首次在遥感目标检测领域探索大型和选择性核机制。

专注于图像领域,主要研究内容包括计算机视觉和深度学习,特别是在图像分类、目标检测和图像生成等方面有深入的研究和实践经验。 2864

信号检测算法的MATLAB仿真:能量检测、循环平稳检测和匹配滤波检测

根据具体的应用场景和要求,选择合适的信号检测算法可以提高系统的性能和可靠性。在无线电通信中,信号检测是一项重要的任务,它用于检测和识别接收到的信号。在本文中,我们将介绍三种常用的信号检测算法:能量检测、循环平稳检测和匹配滤波检测,并提供相应的MATLAB源代码进行仿真实现。在上述代码中,我们首先设置了能量检测的阈值,然后生成了一个包含1000个服从正态分布的随机信号样本的信号。在上述代码中,我们首先设置了信号模板,然后生成了一个包含信号模板的信号样本。最后,通过比较相关性的最大值与阈值来判断信号是否存在。

PixelLancer的博客 1363

Apollo配置发布原理解析

本文主要讲解Apollo配置发布原理,深入浅出通俗易懂的说明了Apollo配置发布过程中的,发送 ReleaseMessage 原理、Config Service 通知客户端原理、Client 客户端读取设计原理。

小明的Java问道之路 2038

【Pix4d精品教程】Pix4d中央子午线细化设置(测区跨两个分带)

本文介绍了在Pix4d软件中通过修改中央子午线设置来解决跨分带测区刺点问题的方法。针对测区跨3度分带(如105°和108°之间)时像控点与靶标点偏移较大的情况,建议将中央子午线设为测区中心(如106.5°)。具体操作步骤包括:修改投影文件中的中央子午线参数,选择新的输出坐标系配置文件。该方法能有效提高像控点刺点效率,为航测内业数据处理提供便利。操作简单实用,适合大比例尺测图项目中跨分带测区的数据处理需求。

智慧空间实验室 5527

深入解析Apollo配置中心:Instance与实时推送机制

Apollo配置中心通过"客户端长轮询+服务端事件驱动"机制实现配置实时推送。ConfigService通过客户端的配置请求(携带appId/IP等信息)和长轮询连接动态感知Instance(应用实例),当配置变更时,后台任务扫描数据库变更并立即通知相关客户端。客户端通过RemoteConfigRepository与ConfigService交互,采用多级缓存(内存+本地文件)确保高可用。服务端核心组件包括处理长轮询的NotificationControllerV2、配置获取接口Conf

油墨香^-^的博客 867

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

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

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

m0_37268363的博客 1093

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

apollo源码(2)-client

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

shandadadada的博客 660

【架构师视角系列】Apollo配置中心之Client端(二)

架构介绍会从分层、职责、关系以及运行负责四个维度对Apollo配置中心的client端进行源码解析

leeboyce的博客 1511

Apollo配置中心总体设计

Apollo配置中心源码解析 一、总体设计 基础模型模型介绍 用户在配置中心对配置进行修改并发布 Apollo配置中心通知Apollo客户端有配置更新 Apollo客户端拉取Apollo配置中心最新配置,更新本地并通知到应用 架构模块 介绍: Config-Service提供配置的读取、推送功能,服务对象客户端(Client) Admin-Service...

重点在于记录 443

Apollo配置管理:四层实体结构解析

Apollo配置中心采用四级实体结构(App-Cluster-Namespace-Item)管理配置数据,支持私有和公共命名空间。公共命名空间可跨应用关联复用,实现配置共享。客户端通过指定命名空间加载配置,并支持热更新监听。系统提供灰度发布、权限控制等高级特性,通过长轮询机制实现配置实时推送。最佳实践建议按功能模块划分命名空间,将通用配置放入公共命名空间,并利用灰度发布降低变更风险。

油墨香^-^的博客 1101
上一篇: 思考个问题,Java 最多支持多少个线程?
下一篇: 2020 年 5 月编程语言排行榜,Java 掉到第二!
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值