如何在apache kafka中获取所有主题? [英] How to get All Topics in apache kafka?

查看:74
本文介绍了如何在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道具如下:字符串zkConnect ="127.0.0.1:2181";而Zookeeper运行得很好.
请帮助大家.

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中获取所有主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆