本文介绍了如何在 apache kafka 中获取所有主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    @RequestMapping(value = "/getTopics",method = RequestMethod.GET)
    @ResponseBody
    public Response getAllTopics() {
        ZkClient zkClient = new ZkClient(ZookeeperProps.zookeeperURL, ZookeeperProps.connectionTimeoutMs,
                ZookeeperProps.sessionTimeoutMs, ZKStringSerializer$.MODULE$);
        Seq<String> topics = ZkUtils.getAllTopics(zkClient);
        scala.collection.Iterator<String> topicIterator = topics.iterator();
        String allTopics = "";
        while(topicIterator.hasNext()) {
            allTopics+=topicIterator.next();
            allTopics+="\n";
        }

        Response response = new Response();
        response.setResponseMessage(allTopics);
        return response;

    }

我是 apache kafka 的新手.现在试图用zookeeper理解kafka.我想获取与 zookeeper 相关的主题.所以我正在尝试以下事情
a:) 首先我制作了zookeeper客户端,如下所示:

I am novice in apache kafka.Now a days trying to understand kafka with zookeeper. I want to fetch the topics associated with zookeeper. so I am trying following things
a:) first i made the zookeeper client as shown below :

ZkClient(ZookeeperProps.zookeeperURL, ZookeeperProps.connectionTimeoutMs, ZookeeperProps.sessionTimeoutMs, ZKStringSerializer$.MODULE$);
Seq<String> topics = ZkUtils.getAllTopics(zkClient);

但是在使用 Java 代码执行时,主题是空白的.我不明白这里有什么问题.我的 Zookeeper 道具如下: String zkConnect = "127.0.0.1:2181";并且动物园管理员运行得非常好.
请大家帮忙.

but topics is blank set while executing with Java code.I am not getting what is problem here.My Zookeeper Props is as follow : String zkConnect = "127.0.0.1:2181"; And zookeeper is running perfectly fine.
Please help guys.

推荐答案

很简单.(我的示例是用 Java 编写的,但在 Scala 中几乎相同.)

It's pretty simple. (My example is written in Java, but it would be almost the same in Scala.)

import java.util.List;

import org.apache.zookeeper.ZooKeeper;

public class KafkaTopicListFetcher {

    public static void main(String[] args) throws Exception {
        ZooKeeper zk = new ZooKeeper("localhost:2181", 10000, null);
        List<String> topics = zk.getChildren("/brokers/topics", false);
        for (String topic : topics) {
            System.out.println(topic);
        }
    }
}

当我有三个主题时的结果:test、test2和test 3

The result when I have three topics: test, test2, and test 3

test
test2
test3

下图是我为自己的博文画的.当您了解 Kafka 使用的 ZooKeeper 树的结构时,这将很有帮助.(这里看起来很小.请在新标签页中打开图片并放大.)

The picture below is what I drew for my own blog posting. It would be helpful when you understand the structure of ZooKeeper tree that Kafka uses. (It looks pretty small here. Open the image in a new tab and zoom in please.)

这篇关于如何在 apache kafka 中获取所有主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 20:22