在java中创建前检查kafka中topic的存在性

cgyqldqp  于 2021-06-08  发布在  Kafka
关注(0)|答案(3)|浏览(1032)

我正在尝试使用以下方法在Kafka0.8.2中创建一个主题:

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

如果我在本地多次运行代码进行测试,这将失败,因为主题已经创建。在创建主题之前,是否有方法检查主题是否存在?这个 TopicCommand api似乎没有返回任何 listTopics 或者 describeTopic .

dohp0rv5

dohp0rv51#

public static void createKafkaTopic(String sourceTopicName, String sinkTopicName, String responseTopicName, String kafkaUrl) {

    try {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
        AdminClient kafkaAdminClient = KafkaAdminClient.create(properties);
        ListTopicsResult topics = kafkaAdminClient.listTopics();
        Set <String> names = topics.names().get();

        boolean containsSourceTopic = names.contains(sourceTopicName);
        boolean containsSinkTopic = names.contains(sinkTopicName);
        boolean containsResponseTopic = names.contains(responseTopicName);

        if (!containsResponseTopic && !containsSinkTopic && !containsSourceTopic) {
            CreateTopicsResult result = kafkaAdminClient.createTopics(
                    Stream.of(sourceTopicName, sinkTopicName, responseTopicName).map(
                            name -> new NewTopic(name, 1, (short) 1)
                    ).collect(Collectors.toList())
            );
            result.all().get();
            LOG.info("new sourceTopicName: {}, sinkTopicName: {}, responseTopicName: {} are created",
                    sourceTopicName, sinkTopicName, responseTopicName);
        }
    } catch (ExecutionException | InterruptedException e) {
        LOG.info("Error message {}", e.getMessage());
    }
}
ffscu2ro

ffscu2ro2#

您可以从kakfa客户端版本0.11.0.0使用adminclient
示例代码:

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);
    }
3lxsmp7m

3lxsmp7m3#

为此,可以使用 AdminUtils.topicExists(ZkUtils zkClient, String topic) ,它会回来的 true 如果主题已经存在, false 否则。
你的代码应该是这样的:

if (!AdminUtils.topicExists(zkClient, myTopic)){
    AdminUtils.createTopic(zkClient, myTopic, 2, 1, properties);
}

相关问题