Apache Pulsar中TopicLookup请求处理的逻辑是什么

本篇内容主要讲解“Apache Pulsar中TopicLookup请求处理的逻辑是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Apache Pulsar中TopicLookup请求处理的逻辑是什么”吧!

实际的核心逻辑是这2行代码

LookupOptions options = LookupOptions.builder()
                        .authoritative(authoritative)
                        .advertisedListenerName(advertisedListenerName)
                        .loadTopicsInBundle(true)    // 这里这个条件是true
                        .build();
                
pulsarService.getNamespaceService().getBrokerServiceUrlAsync(topicName, options)

这里传递的参数将loadTopicsInBundle 设置了成true。我们看下在处理lookup请求过程中是否有loadtopic的逻辑。

NamespaceService.findBrokerServiceUrl

这个函数我们注意到有 ownershipCache.getOwnerAsyncsearchForCandidateBroker 这2个地方没有细说

我们先看一下ownershipCache

private CompletableFuture<Optional<LookupResult>> findBrokerServiceUrl(
            NamespaceBundle bundle, LookupOptions options) {
        ....
        return targetMap.computeIfAbsent(bundle, (k) -> {
            ...
            ownershipCache.getOwnerAsync(bundle)
                    .thenAccept(nsData -> {
               // nsData : Optional<NamespaceEphemeralData>
                if (!nsData.isPresent()) {
                    ...
                      
                    // 目前还没有人负责这个bundle 尝试查找这个bundle的owner
                    pulsar.getExecutor().execute(() -> {
                       searchForCandidateBroker(bundle, future, options);
                    });
                  
                    ...
                }
                      
            ...
        });
    }

OwnerShipCache类

从javadoc 里面可以知道这个类的主要功能。

  • cache zk里面关于 service unit 的ownership信息

  • 提供zk的读写功能

    • 可以用来查找owner信息

    • 可以用来获取一个 service unit 的ownership

getOwnerAsync 这个方法主要是查看zk cache里面是否有信息,如果没有信息,则尝试读取zk节点,

如果节点有信息则说明有人拿到了这个bundle的ownership

如果这个节点就是当前机器,则会通知bundle load的信息给listener

如果这个节点没有信息,说明当前还没有人负责这个bundle。

// org.apache.pulsar.broker.namespace.OwnerShipCache

public 
CompletableFuture<Optional<NamespaceEphemeralData>> 
getOwnerAsync(NamespaceBundle suName) 
{
        // 这里的路径是 /namespace/{namespace}/0x{lowerEndpoint}_0x{upperEndpoint}
        String path = ServiceUnitZkUtils.path(suName);

        // ownedBundleFuture 还是一个 AsyncLoadingCache 
        // 这里不会尝试去加载这个cache信息,因为调用的getIfPresent
        CompletableFuture<OwnedBundle> ownedBundleFuture = ownedBundlesCache.getIfPresent(path);
       
        // 如果之前有内容的话就说明当前broker是owner(这部分逻辑在cache的加载代码里面,后面会说)
        if (ownedBundleFuture != null) {
            // Either we're the owners or we're trying to become the owner.
            return ownedBundleFuture.thenApply(serviceUnit -> {
                // We are the owner of the service unit
                return Optional.of(serviceUnit.isActive() ? selfOwnerInfo : selfOwnerInfoDisabled);
            });
        }

        // 如果cache里面没有,我们确认下当前的owner是谁。
        // If we're not the owner, we need to check if anybody else is
        return resolveOwnership(path)
                .thenApply(optional -> optional.map(Map.Entry::getKey));
}


private CompletableFuture<Optional<Map.Entry<NamespaceEphemeralData, Stat>>> resolveOwnership(String path) {
        
        return ownershipReadOnlyCache.getWithStatAsync(path)      // 这个逻辑是从zk里面读取这个bundle路径下的内容
          .thenApply(optionalOwnerDataWithStat -> {
            
            // 如果这个路径下有数据,则说明有人已经成功获取了这个bundle的ownership信息
            if (optionalOwnerDataWithStat.isPresent()) {
                Map.Entry<NamespaceEphemeralData, Stat> ownerDataWithStat = optionalOwnerDataWithStat.get();
                Stat stat = ownerDataWithStat.getValue();
              
                // 如果这个zk临时节点的owner就是当前的broker
                if (stat.getEphemeralOwner() == localZkCache.getZooKeeper().getSessionId()) {
                    LOG.info("Successfully reestablish ownership of {}", path);
                  
                    // 这里是更新缓存的逻辑
                    OwnedBundle ownedBundle = new OwnedBundle(ServiceUnitZkUtils.suBundleFromPath(path, bundleFactory));
                    if (selfOwnerInfo.getNativeUrl().equals(ownerDataWithStat.getKey().getNativeUrl())) {
                        ownedBundlesCache.put(path, CompletableFuture.completedFuture(ownedBundle));
                    }
                    ownershipReadOnlyCache.invalidate(path);
                    // 这里会通知callback(和主要逻辑无关)
                    namespaceService.onNamespaceBundleOwned(ownedBundle.getNamespaceBundle());
                }
            }
            
            // 这里返回的是一个Optional对象,如果这个节点不存在的话返回的实际是一个Empty
            // 说明这个时候没有人负责这个bundle
            // 也可能返回带有信息的optional,这时候负责这个节点的broker可能是当前机器也可能是其他机器。
            return optionalOwnerDataWithStat;
        });
    }

我们看一下如果没有任何人负责这个bundle的情况。

NamespaceService.searchForCandidateBroker

这个方法的逻辑是选出当前这个bundle的owner是哪个broker

主要依靠LeaderElectionServiceLoadManager 选出。

如果选出来的broker是本机的话,则会尝试获取这个bundle的ownership。

如果是其他机器的话则会把这个请求转发给其他机器,请求其他机器来获取ownership。

private void searchForCandidateBroker(NamespaceBundle bundle,
                                          CompletableFuture<Optional<LookupResult>> lookupFuture,
                                          LookupOptions options) {
        ...
          
        // 首先会按照一定逻辑来选出这个bundle的可能的broker节点
        String candidateBroker = null;

        ...
        boolean authoritativeRedirect = les.isLeader();

        try {
            // check if this is Heartbeat or SLAMonitor namespace
            ...

            if (candidateBroker == null) {
                if (options.isAuthoritative()) {
                    // leader broker already assigned the current broker as owner
                    candidateBroker = pulsar.getSafeWebServiceAddress();
                } else 
                  
                  // 如果这个LeaderElectionService 是leader ||
                  // 不是中心化的loadManager(这个是均衡负载用的)|| 
                  // 如果当前这个leader的broker还不是active的
                  if (!this.loadManager.get().isCentralized()
                        || pulsar.getLeaderElectionService().isLeader()

                        // If leader is not active, fallback to pick the least loaded from current broker loadmanager
                        || !isBrokerActive(pulsar.getLeaderElectionService().getCurrentLeader().getServiceUrl())
                ) {
                    
                    // 从loadManager选一个负载最轻的broker出来
                    Optional<String> availableBroker = getLeastLoadedFromLoadManager(bundle);
                    if (!availableBroker.isPresent()) {
                        lookupFuture.complete(Optional.empty());
                        return;
                    }
                    candidateBroker = availableBroker.get();
                    authoritativeRedirect = true;
                } else {
                    // forward to leader broker to make assignment
                    candidateBroker = pulsar.getLeaderElectionService().getCurrentLeader().getServiceUrl();
                }
            }
        } catch (Exception e) {
            ...
        }

  			// 到这里就选出一个候选的broker地址了
        try {
            checkNotNull(candidateBroker);
            // 如果这个候选broker就是当前机器
            if (candidateBroker.equals(pulsar.getSafeWebServiceAddress())) {
                ...  
                // 这里使用ownerShipCache尝试获取这个bundle的ownership
                ownershipCache.tryAcquiringOwnership(bundle)
                  .thenAccept(ownerInfo -> {
                    ...
                       
                        // 这里就是文章开始的时候说的是否需要load 所有在bundle里面的topic
                        if (options.isLoadTopicsInBundle()) {
                            // Schedule the task to pre-load topics
                            pulsar.loadNamespaceTopics(bundle);
                        }
                    
                    
                        // find the target
                        // 走到这里说明已经把当前的broker作为这个bundle的owner了,直接返回本机的信息给请求者
                            lookupFuture.complete(Optional.of(new LookupResult(ownerInfo)));
                            return;
                    }
                }).exceptionally(exception -> {
                   ...
                });

            } else {
                ...
                 
                // 这里是把这个lookup 请求转发给其他broker
                // Load managed decider some other broker should try to acquire ownership
                // Now setting the redirect url
                createLookupResult(candidateBroker, authoritativeRedirect, options.getAdvertisedListenerName())
                        .thenAccept(lookupResult -> lookupFuture.complete(Optional.of(lookupResult)))
                        .exceptionally(ex -> {
                            lookupFuture.completeExceptionally(ex);
                            return null;
                        });

            }
        } catch (Exception e) {
            ...
        }
    }

OwnershipCache.tryAcquiringOwnership

这里就是尝试获取这个bundle的ownership的逻辑了。

只需要在zk上记录当前节点的信息就可以了。

(也会有维护这个cache的逻辑)

public CompletableFuture<NamespaceEphemeralData> 
  tryAcquiringOwnership(NamespaceBundle bundle) throws Exception {
        String path = ServiceUnitZkUtils.path(bundle);

        CompletableFuture<NamespaceEphemeralData> future = new CompletableFuture<>();

        ...

        LOG.info("Trying to acquire ownership of {}", bundle);

  			// 这里调用的是get,这个方法会触发cache加载的逻辑。
  
        // Doing a get() on the ownedBundlesCache will trigger an async ZK write to acquire the lock over the
        // service unit
        ownedBundlesCache.get(path)
        .thenAccept(namespaceBundle -> {
            // 到这里说明已经获得了这个bundle的ownership了,直接返回。
            LOG.info("Successfully acquired ownership of {}", path);
            namespaceService.onNamespaceBundleOwned(bundle);
            future.complete(selfOwnerInfo);
          
          
        }).exceptionally(exception -> {
            // 这里如果加载过程中出现问题(可能是其他人成为了leader)
            // Failed to acquire ownership
            if (exception instanceof CompletionException
                    && exception.getCause() instanceof KeeperException.NodeExistsException) {
              
                // 确认当前的leader是谁
                resolveOwnership(path)
                  .thenAccept(optionalOwnerDataWithStat -> {
                    // 这里会拿到之前成功获得ownership的节点信息
                    if (optionalOwnerDataWithStat.isPresent()) {
                        Map.Entry<NamespaceEphemeralData, Stat> ownerDataWithStat = optionalOwnerDataWithStat.get();
                        NamespaceEphemeralData ownerData = ownerDataWithStat.getKey();
                        Stat stat = ownerDataWithStat.getValue();
                        if (stat.getEphemeralOwner() != localZkCache.getZooKeeper().getSessionId()) {
                            LOG.info("Failed to acquire ownership of {} -- Already owned by broker {}",
                                    path, ownerData);
                        }
                        // 直接返回即可
                        future.complete(ownerData);
                    } else {
                        ...
                    }{
                }).exceptionally(ex -> {
                    ....
                });
              
            } else {
                ...
            }

            return null;
        });

        return future;
    }

OwnershipCache 加载逻辑

这里逻辑比较简单,序列化本机的连接信息,写入到这个bundle的path下面就行了

private class OwnedServiceUnitCacheLoader implements AsyncCacheLoader<String, OwnedBundle> {

        @SuppressWarnings("deprecation")
        @Override
        public CompletableFuture<OwnedBundle> asyncLoad(String namespaceBundleZNode, Executor executor) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Acquiring zk lock on namespace {}", namespaceBundleZNode);
            }

            byte[] znodeContent;
            try {
                znodeContent = jsonMapper.writeValueAsBytes(selfOwnerInfo);
            } catch (JsonProcessingException e) {
                // Failed to serialize to JSON
                return FutureUtil.failedFuture(e);
            }

            CompletableFuture<OwnedBundle> future = new CompletableFuture<>();
            ZkUtils.asyncCreateFullPathOptimistic(localZkCache.getZooKeeper(), namespaceBundleZNode, znodeContent,
                    Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, (rc, path, ctx, name) -> {
                        if (rc == KeeperException.Code.OK.intValue()) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Successfully acquired zk lock on {}", namespaceBundleZNode);
                            }
                            ownershipReadOnlyCache.invalidate(namespaceBundleZNode);
                            future.complete(new OwnedBundle(
                                    ServiceUnitZkUtils.suBundleFromPath(namespaceBundleZNode, bundleFactory)));
                        } else {
                            // Failed to acquire lock
                            future.completeExceptionally(KeeperException.create(rc));
                        }
                    }, null);

            return future;
        }
    }

加载bundle下所有topic

到这里我们已经可以拿到bundle的ownership了。我们看一下之前加载所有topic的逻辑。

PulsarService.loadNamespaceTopics

public void loadNamespaceTopics(NamespaceBundle bundle) {
        executor.submit(() -> {
            NamespaceName nsName = bundle.getNamespaceObject();
            List<CompletableFuture<Topic>> persistentTopics = Lists.newArrayList();
            long topicLoadStart = System.nanoTime();

            for (String topic : getNamespaceService().getListOfPersistentTopics(nsName).join()) {
                try {
                    TopicName topicName = TopicName.get(topic);
                    if (bundle.includes(topicName)) {
                        // 到这里会创建一个Topic对象保存在BrokerService里面
                        // 这部分后面会说,涉及到 ManagedLedger 里面的初始化
                        CompletableFuture<Topic> future = brokerService.getOrCreateTopic(topic);
                        if (future != null) {
                            persistentTopics.add(future);
                        }
                    }
                } 
                ...
            }
            ...
            return null;
        });
    }

NamespaceService.getListOfPersistentTopics

这里就比较容易了

读取zk的/managed-ledgers/%s/persistent所有子节点即可。

public CompletableFuture<List<String>> getListOfPersistentTopics(NamespaceName namespaceName) {
        // For every topic there will be a managed ledger created.
        String path = String.format("/managed-ledgers/%s/persistent", namespaceName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting children from managed-ledgers now: {}", path);
        }

        return pulsar.getLocalZkCacheService().managedLedgerListCache().getAsync(path)
                .thenApply(znodes -> {
                    List<String> topics = Lists.newArrayList();
                    for (String znode : znodes) {
                        topics.add(String.format("persistent://%s/%s", namespaceName, Codec.decode(znode)));
                    }

                    topics.sort(null);
                    return topics;
                });
    }

到此,相信大家对“Apache Pulsar中TopicLookup请求处理的逻辑是什么”有了更深的了解,不妨来实际操作一番吧!这里是编程之家网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


可以认为OpenFeign是Feign的增强版,不同的是OpenFeign支持Spring MVC注解。OpenFeign和Feign底层都内置了Ribbon负载均衡组件,在导入OpenFeign依赖后无需专门导入Ribbon依赖,用做客户端负载均衡,去调用注册中心服务。
为进一步规范小程序交易生态、提升用户购物体验、满足用户在有交易的小程序中便捷查看订单信息的诉求,自2022年12月31日起,对于有“选择商品/服务-下单-支付”功能的小程序,需按照平台制定的规范,在小程序内设置订单中心页。开发者可通过小程序代码提审环节,或通过「设置-基础设置-小程序订单中心path设置」模块设置订单中心页path。1、 新注册或有版本迭代需求的小程序,可在提审时通过参数配置该商家小程序的订单中心页path。2、无版本迭代需求的小程序,可在小程序订单中心path设置入口进行设置。
云原生之使用Docker部署Dashdot服务器仪表盘
本文主要描述TensorFlow之回归模型的基本原理
1.漏洞描述Apache Druid 是一个集时间序列数据库、数据仓库和全文检索系统特点于一体的分析性数据平台。Apache Druid对用户指定的HTTP InputSource没有做限制,并且Apache Druid默认管理页面是不需要认证即可访问的,可以通过将文件URL传递给HTTP InputSource来绕过。因此未经授权的远程攻击者可以通过构造恶意参数读取服务器上的任意文件,造成服务器敏感性信息泄露。2.影响版本Apache Druid &lt;= 0.21.13...
内部类(当作类中的一个普通成员变量,只不过此成员变量是class的类型):一个Java文件中可以包含多个class,但是只能有一个public class 如果一个类定义在另一个类的内部,此时可以称之为内部类使用:创建内部类的时候,跟之前的方法不一样,需要在内部类的前面添加外部类来进行修饰 OuterClass.InnerClass innerclass = new OuterClass().new InnerClass();特点:1.内部类可以方便的访问外部类的私有属性...
本文通过解读国密的相关内容与标准,呈现了当下国内技术环境中对于国密功能支持的现状。并从 API 网关 Apache APISIX 的角度,带来有关国密的探索与功能呈现。作者:罗泽轩,Apache APISIX PMC什么是国密顾名思义,国密就是国产化的密码算法。在我们日常开发过程中会接触到各种各样的密码算法,如 RSA、SHA256 等等。为了达到更高的安全等级,许多大公司和国家会制定自己的密码算法。国密就是这样一组由中国国家密码管理局制定的密码算法。在国际形势越发复杂多变的今天,密码算法的国产化
CENTOS环境Apache最新版本httpd-2.4.54编译安装
Apache HTTPD是一款HTTP服务器,它可以通过mod_php来运行PHP网页。影响版本:Apache 2.4.0~2.4.29 存在一个解析漏洞;在解析PHP时,将被按照PHP后缀进行解析,导致绕过一些服务器的安全策略。我们查看一下配置:读取配置文件,前三行的意思是把以 结尾的文件当成 文件执行。问题就在它使用的是 符号匹配的,我们都知道这个符号在正则表达式中的意思是匹配字符串的末尾,是会匹配换行符的,那么漏洞就这样产生了。 进入容器里,打开index.php,发现如果文件后缀名为 php、
apache Hop现在好像用的人很少, 我就自己写一个问题收集的帖子吧, 后面在遇到什么问题都会在该文章上同步更新
2.启动容器ps:注意端口占用,当前部署在 8080 端口上了,确保宿主机端口未被占用,不行就换其他端口ps:用户名和密码都是 admin,一会用于登录,其他随便填5.下载一个官方提供的样例数据库【可跳过】ps:此步国内无法访问,一般下载不了,能下的就下,不能下的跳过就行了,一会配置自己的数据库7.访问登录页面ps:注意端口是上面自己配置的端口,账号密码是 admin依次点击 Settings → Database Connections点击 DATABASE 就可以配置自己的数据库了
String类的常用方法1. String类的两种实例化方式1 . 直接赋值,在堆上分配空间。String str = "hello";2 . 传统方法。通过构造方法实例化String类对象String str1 = new String("Hello");2.采用String类提供的equals方法。public boolean equals(String anotherString):成员方法 str1.equals(anotherString);eg:publi
下载下载地址http://free.safedog.cn下载的setup:安装点击下面的图标开始安装:可能会提示:尝试先打开小皮面板的Apache服务:再安装安全狗:填入服务名:如果服务名乱写的话,会提示“Apache服务名在此机器上查询不到。”我干脆关闭了这个页面,直接继续安装了。安装完成后,需要进行注册一个账户,最后看到这样的界面:查看配置:...
一、问题描述一组生产者进程和一组消费者进程共享一个初始为空、大小n的缓冲区,只有缓冲区没满时,生产者才能把资源放入缓冲区,否则必须等待;只有缓冲区不为空时,消费者才能从中取出资源,否则必须等待。由于缓冲区是临界资源,它只允许一个生产者放入资源,或一个消费者从中取出资源。二、问题分析(1)、关系分析。生产者和消费者对缓冲区互斥访问是互斥关系,同时生产者和消费者又是一个相互协作的关系,只有生产者生产之后,消费者只能才能消费,它们还是同步关系。(2)、整理思路。只有生产生产者和消费者进程,正好是这两个进程
依赖注入的英文名是Dependency Injection,简称DI。事实上这并不是什么新兴的名词,而是软件工程学当中比较古老的概念了。如果要说对于依赖注入最知名的应用,大概就是Java中的Spring框架了。Spring在刚开始其实就是一个用于处理依赖注入的框架,后来才慢慢变成了一个功能更加广泛的综合型框架。我在学生时代学习Spring时产生了和绝大多数开发者一样的疑惑,就是为什么我们要使用依赖注入呢?现在的我或许可以给出更好的答案了,一言以蔽之:解耦。耦合度过高可能会是你的项目中一个比较
<dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>使用人数最多的版本</version></dependency>importorg.apache.velocity.Template;importorg.apache.velo
Java Swing皮肤包前言:一.皮肤包分享二.皮肤包的使用1.先新建一个项目。2.导入皮肤包1.先导入我们刚刚下载的jar文件,右键项目demo即可2.如果右键没有这个选项,记得调为下图模式3.点击下图蓝色圆圈处4.找到刚刚下载的jar文件,点击打开即可5.我们看一下效果,是不是比原生的好看前言:因为Java Swing自身皮肤包不是很好看,甚至有点丑,怎么让你的界面更加好看,这里就需要用到皮肤包,我发现了一个还不错的皮肤包,让你的界面美观了几个等级。废话不多说。一.皮肤包分享百度网盘分享链接:
一、前言在做Java项目开发过程中,涉及到一些数据库服务连接配置、缓存服务器连接配置等,通常情况下我们会将这些不太变动的配置信息存储在以 .properties 结尾的配置文件中。当对应的服务器地址或者账号密码信息有所变动时,我们只需要修改一下配置文件中的信息即可。同时为了让Java程序可以读取 .properties配置文件中的值,Java的JDK中提供了java.util.Properties类可以实现读取配置文件。二、Properties类Properties 类位于 java.util.Pro
Mybatis环境JDK1.8Mysql5.7maven 3.6.1IDEA回顾JDBCMysqlJava基础MavenJunitSSM框架:配置文件的最好的方式:看官网文档Mybatis1、Mybatis简介1.1 什么是Mybatis如何获得Mybatismaven仓库:中文文档:https://mybatis.org/mybatis-3/zh/index.htmlGithub:1.2 持久化数据持久化持久化就是将程序的数据在持久状态和瞬时状态转