kafkatopic操作
package com.liuze.learnkafka;
import org.apache.kafka.clients.admin.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
import java.util.concurrent.ExecutionException;
@SpringBootTest
class LearnKafkaApplicationTests {
private static final String KAFKA_TOPIC = "myTopic";
public static AdminClient intiAdminClient() {
Properties props = new Properties();
props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "ip:9092,ip:9093,ip:9094");
return AdminClient.create(props);
}
@Test
public void test() {
AdminClient adminClient = intiAdminClient();
NewTopic newTopic = new NewTopic("LIUZE", 6, (short) 3);
CreateTopicsResult topics = adminClient.createTopics(Collections.singletonList(newTopic));
try {
topics.all().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void topicList() {
AdminClient adminClient = intiAdminClient();
ListTopicsOptions options = new ListTopicsOptions();
options.listInternal(true);
ListTopicsResult listTopicsResult = adminClient.listTopics(options);
try {
Set<String> strings = listTopicsResult.names().get();
strings.forEach(System.out::println);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void delTopic() {
AdminClient adminClient = intiAdminClient();
DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(Collections.singletonList("xdclass-cluster-topic"));
try {
Void unused = deleteTopicsResult.all().get();
System.out.println(unused);
topicList();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void detail() throws ExecutionException, InterruptedException {
AdminClient adminClient = intiAdminClient();
DescribeTopicsResult describeTopicsResult = adminClient.describeTopics(Collections.singletonList("xdclass-cluster-topic"));
Map<String, TopicDescription> stringTopicDescriptionMap = describeTopicsResult.all().get();
stringTopicDescriptionMap.forEach((v, k) -> System.out.println(v + " " + k));
}
@Test
public void addTopicPartition() throws ExecutionException, InterruptedException {
AdminClient adminClient = intiAdminClient();
NewPartitions newPartitions = NewPartitions.increaseTo(5);
HashMap<String, NewPartitions> hashMap = new HashMap<>(1);
hashMap.put(KAFKA_TOPIC, newPartitions);
CreatePartitionsResult partitions = adminClient.createPartitions(hashMap);
partitions.all().get();
}
}