在使用Java创建之前检查kafka中是否存在主题

时间:2015-06-01 11:12:14

标签: java apache-kafka

我正在尝试使用:

在kafka 0.8.2中创建一个主题
AdminUtils.createTopic(zkClient, myTopic, 2, 1, properties);

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

3 个答案:

答案 0 :(得分:4)

为此,您可以使用方法AdminUtils.topicExists(ZkUtils zkClient, String topic),如果主题已存在,则会返回true,否则返回false

您的代码将是这样的:

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

答案 1 :(得分:2)

您可以从kakfa-client版本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);
    }

答案 2 :(得分:0)

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());
    }
}