NotificationControllerV2:notifications/v2:实现长轮循,监听配置变更、返回,结束长轮循

本文介绍Apollo配置服务中NotificationControllerV2组件如何通过长轮询监听配置变更并通知客户端。涉及ReleaseMessageListener监听器注册、客户端请求处理及配置通知流程。

NotificationControllerV2:notifications/v2:实现长轮循,监听配置变更、返回,结束长轮循

LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code and KPI, Keep progress,make a better result.
Survive during the day and develop at night。

目录

概 述

NotificationControllerV2实现了ReleaseMessageListener,具体什么时候注册的监听器请参考:ConfigServiceAutoConfiguration

/**
	   * 监听器注册,namespaces变更后接收消息
	   * @return
	   */
    @Bean
    public ReleaseMessageScanner releaseMessageScanner() {
      ReleaseMessageScanner releaseMessageScanner = new ReleaseMessageScanner();
      //0. handle release message cache
      releaseMessageScanner.addMessageListener(releaseMessageServiceWithCache);
      //1. handle gray release rule
      releaseMessageScanner.addMessageListener(grayReleaseRulesHolder);
      //2. handle server cache
      releaseMessageScanner.addMessageListener(configService);
      releaseMessageScanner.addMessageListener(configFileController);
      //3. notify clients
      releaseMessageScanner.addMessageListener(notificationControllerV2);
      releaseMessageScanner.addMessageListener(notificationController);
      return releaseMessageScanner;
    }

进入主流程2.1客户端请求,ConfigSerivce通知配置变更,这里是利用Spring DeferredResult实现长轮循

@GetMapping
  public DeferredResult<ResponseEntity<List<ApolloConfigNotification>>> pollNotification(
      @RequestParam(value = "appId") String appId,
      @RequestParam(value = "cluster") String cluster,
      @RequestParam(value = "notifications") String notificationsAsString,
      @RequestParam(value = "dataCenter", required = false) String dataCenter,
      @RequestParam(value = "ip", required = false) String clientIp) {
    List<ApolloConfigNotification> notifications = null;
 
    try {
    	//因为一个客户端可以订阅过个namespace所以是list
      notifications =
          gson.fromJson(notificationsAsString, notificationsTypeReference);
    } catch (Throwable ex) {
      Tracer.logError(ex);
    }
 
    if (CollectionUtils.isEmpty(notifications)) {
      throw new BadRequestException("Invalid format of notifications: " + notificationsAsString);
    }

DeferredResultWrapper deferredResultWrapper = new DeferredResultWrapper(bizConfig.longPollingTimeoutInMilli());
    //namespaces集合
    Set<String> namespaces = Sets.newHashSet();
    //客户端通知的map,key:namespaces名;value:通知编号
    Map<String, Long> clientSideNotifications = Maps.newHashMap();
    //key:namespaces名
	  //过滤ApolloConfigNotification
    Map<String, ApolloConfigNotification> filteredNotifications = filterNotifications(appId, notifications);
 
    for (Map.Entry<String, ApolloConfigNotification> notificationEntry : filteredNotifications.entrySet()) {
      String normalizedNamespace = notificationEntry.getKey();
      ApolloConfigNotification notification = notificationEntry.getValue();
      //添加到namespaces里
      namespaces.add(normalizedNamespace);
      //添加通知客户端map
      clientSideNotifications.put(normalizedNamespace, notification.getNotificationId());
      // 记录名字被归一化的 Namespace 。因为,最终返回给客户端,使用原始的 Namespace 名字,否则客户端无法识别。
      if (!Objects.equals(notification.getNamespaceName(), normalizedNamespace)) {
        deferredResultWrapper.recordNamespaceNameNormalizedResult(notification.getNamespaceName(), normalizedNamespace);
      }
    }

if (CollectionUtils.isEmpty(namespaces)) {
      throw new BadRequestException("Invalid format of notifications: " + notificationsAsString);
    }
	//组装Watch key集合
    Multimap<String, String> watchedKeysMap =
        watchKeysUtil.assembleAllWatchKeys(appId, cluster, namespaces, dataCenter);
	//生成watch key 集合
    Set<String> watchedKeys = Sets.newHashSet(watchedKeysMap.values());

deferredResultWrapper
          .onTimeout(() -> logWatchedKeys(watchedKeys, "Apollo.LongPoll.TimeOutKeys"));
	//注册结束事件
    deferredResultWrapper.onCompletion(() -> {
      //unregister all keys
		//移除watch key+deferredResultWrapper出deferredResults
      for (String key : watchedKeys) {
        deferredResults.remove(key, deferredResultWrapper);
      }
      logWatchedKeys(watchedKeys, "Apollo.LongPoll.CompletedKeys");
    });

for (String key : watchedKeys) {
      this.deferredResults.put(key, deferredResultWrapper);
    }
     entityManagerUtil.closeEntityManager();
	//获取最新的ApolloConfigNotification集合
    List<ApolloConfigNotification> newNotifications =
        getApolloConfigNotifications(namespaces, clientSideNotifications, watchedKeysMap,
            latestReleaseMessages);
//	若有更新直接设置结果
    if (!CollectionUtils.isEmpty(newNotifications)) {
      deferredResultWrapper.setResult(newNotifications);
    }
 
    return deferredResultWrapper.getResult();
  }

``
 我们重点看一下getApolloConfigNotifications():获取最新的ApolloConfigNotification集合:
 


`
                     
 
  
 

 



 


小结

NotificationControllerV2:notifications/v2:实现长轮循,监听配置变更、返回,结束长轮循

参考资料和推荐阅读

1.链接: 参考资料.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迅捷的软件产品制作专家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值