我可以作为制作人删除主题吗?或者我可以在写之前删除主题吗

rqqzpn5f  于 2021-06-06  发布在  Kafka
关注(0)|答案(1)|浏览(313)

我有一个生产者提供数据,我们将用于测试我们的网络应用程序和消费者。为此,我想问,是否有一种方法,以删除主题之前,把他们通过生产者?目前,由于我在电脑上使用虚拟机来测试系统,我可以通过cmd。有没有什么办法可以由制片人来做呢( java 语)

yrefmtwq

yrefmtwq1#

您可以在producer实现中包含一些删除主题的代码(可能在最开始的时候)。
下面是一个利用 kafka.admin.AdminUtils.deleteTopic() ,

/**
 * Deletes the named topics
 * @param topicNames The names of the topics to delete
 * @return A set of the names of the topics that were successfully deleted
 */
public String[] deleteTopics(final String...topicNames) {
    if(!connected.get()) throw new IllegalStateException("The KafkaTestServer is not running");
    if(topicNames==null || topicNames.length==0) return new String[0];
    final Set<String> deleted = new LinkedHashSet<String>();
    for(String topicName: topicNames) {
        if(topicName==null || topicName.trim().isEmpty()) {
            try {
                AdminUtils.deleteTopic(zkUtils, topicName.trim());
                deleted.add(topicName.trim());
            } catch (Exception ex) {
                log.warn("Failed to delete topic [" + topicName.trim() + "]", ex);
            }
        }
    }
    return deleted.toArray(new String[deleted.size()]);
}

相关问题