kafka删除topic-使用java代码删除的三种方式
提示,删除topic之前,一定要确认kafka的broker是否有这个配置
delete.topic.enable=true
如果为false是删除不成功的一定要确认是否为true
ps -ef|grep kafka去看kafka的启动参数配置
1.低版本的kafka_2.11
maven依赖
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.11</artifactId> <version>0.9.0.1</version> </dependency>
java代码:
public Map<String,String> deleteTopic(List<String> topics) { if (CollectionUtils.isEmpty(topics)){ return null; } String zkServer = "zk-1-svc:4180,zk-2-svc:4180,zk-3-svc:4180"; int sessionTimeoutMs = 30 * 1000; int connectionTimeoutMs = 30 * 1000; ZkClient client = new ZkClient(zkServer, sessionTimeoutMs, connectionTimeoutMs); client.setZkSerializer(new StringZkSerializer()); // 一定要加上ZkSerializer // Security for Kafka was added in Kafka 0.9.0.1 boolean isSecureKafkaCluster = false; ZkUtils zkUtils = new ZkUtils(client, new ZkConnection(zkServer), isSecureKafkaCluster); Map<String,String> result = new HashMap<>(); for (String topicName : topics) { try { if (!AdminUtils.topicExists(zkUtils,topicName)){ continue; } AdminUtils.deleteTopic(zkUtils, topicName); result.put(topicName,"success"); } catch (Exception e) { logger.error("TopicService-deleteTopic 删除topic失败,topicName={}", topicName, e); result.put(topicName,"fail"); } } client.close(); return result; }
2.高本版的kafka_2.11删除topic方式
maven依赖
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.11</artifactId> <version>1.1.1</version> </dependency>
java代码
public void delete(String topic) { int sessionTimeoutMs = 30 * 1000; int connectionTimeoutMs = 30 * 1000; ZooKeeperClient zooKeeperClient = new ZooKeeperClient("zk-1-svc:4180,zk-2-svc:4180,zk-3-svc:4180",sessionTimeoutMs,connectionTimeoutMs,10, Time.SYSTEM,"",""); KafkaZkClient kafkaZkClient = new KafkaZkClient(zooKeeperClient,false,Time.SYSTEM); try { TopicCommand.deleteTopic(kafkaZkClient, new TopicCommand.TopicCommandOptions( new String[]{"--delete", "--topic", topic})); }catch (Exception e){ System.out.println("fail"); } System.out.println("success"); }
3:kafka客户端自带的删除方式
maven依赖
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>1.1.1</version> </dependency>
java代码
public Map<String, Boolean> deleteTopic(String topicName) { Properties properties = new Properties(); properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "broker-1:9092,broker-2:9092,broker-3:9092"); properties.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, 30000); AdminClient adminClient = AdminClient.create(properties); DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(Collections.singleton(topicName)); Map<String, Boolean> map = new HashMap<>(); try { for (Map.Entry<String, KafkaFuture<Void>> entry : deleteTopicsResult.values().entrySet()) { String topic = entry.getKey(); KafkaFuture<Void> future = entry.getValue(); future.get();//执行 map.put(topic, !future.isCompletedExceptionally()); } } catch (Exception e) { e.printStackTrace(); } return map; }