在Java中创建之前检查kafka中主题的存在 [英] Checking the existence of topic in kafka before creating in Java

查看:69
本文介绍了在Java中创建之前检查kafka中主题的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法在kafka 0.8.2中创建主题:

I am trying to create a topic in kafka 0.8.2 by using :

AdminUtils.createTopic(zkClient, myTopic, 2, 1, properties);

如果我多次在本地运行代码以进行测试,则失败,因为已经创建了该主题.创建主题之前,有没有办法检查主题是否存在? TopicCommand api似乎没有为 listTopics describeTopic 返回任何内容

If I run the code more than once locally for testing, this fails as the topic was already created. Is there a way to check if the topic exists before creating the topic? The TopicCommand api doesn't seem to return anything for listTopics or describeTopic .

推荐答案

您可以使用kakfa-client版本0.11.0.0中的AdminClient

You can use AdminClient from kakfa-client version 0.11.0.0

示例代码:

    Properties config = new Properties();
    config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhist:9091");

    AdminClient admin = AdminClient.create(config);
    ListTopicsResult listTopics = admin.listTopics();
    Set<String> names = listTopics.names().get();
    boolean contains = names.contains("TEST_6");
    if (!contains) {
        List<NewTopic> topicList = new ArrayList<NewTopic>();
        Map<String, String> configs = new HashMap<String, String>();
        int partitions = 5;
        Short replication = 1;
        NewTopic newTopic = new NewTopic("TEST_6", partitions, replication).configs(configs);
        topicList.add(newTopic);
        admin.createTopics(topicList);
    }

这篇关于在Java中创建之前检查kafka中主题的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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