Purge Kafka Topic

后端 未结 19 2390
慢半拍i
慢半拍i 2020-11-28 00:06

Is there a way to purge the topic in kafka?

I pushed a message that was too big into a kafka message topic on my local machine, now I\'m getting an

19条回答
  •  半阙折子戏
    2020-11-28 01:06

    From Java, using the new AdminZkClient instead of the deprecated AdminUtils:

      public void reset() {
        try (KafkaZkClient zkClient = KafkaZkClient.apply("localhost:2181", false, 200_000,
            5000, 10, Time.SYSTEM, "metricGroup", "metricType")) {
    
          for (Map.Entry> entry : listTopics().entrySet()) {
            deleteTopic(entry.getKey(), zkClient);
          }
        }
      }
    
      private void deleteTopic(String topic, KafkaZkClient zkClient) {
    
        // skip Kafka internal topic
        if (topic.startsWith("__")) {
          return;
        }
    
        System.out.println("Resetting Topic: " + topic);
        AdminZkClient adminZkClient = new AdminZkClient(zkClient);
        adminZkClient.deleteTopic(topic);
    
        // deletions are not instantaneous
        boolean success = false;
        int maxMs = 5_000;
        while (maxMs > 0 && !success) {
          try {
            maxMs -= 100;
            adminZkClient.createTopic(topic, 1, 1, new Properties(), null);
            success = true;
          } catch (TopicExistsException ignored) {
          }
        }
    
        if (!success) {
          Assert.fail("failed to create " + topic);
        }
      }
    
      private Map> listTopics() {
        Properties props = new Properties();
        props.put("bootstrap.servers", kafkaContainer.getBootstrapServers());
        props.put("group.id", "test-container-consumer-group");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    
        KafkaConsumer consumer = new KafkaConsumer<>(props);
        Map> topics = consumer.listTopics();
        consumer.close();
    
        return topics;
      }
    

提交回复
热议问题