1.代码示例
public class AdminSample {
private static final String topicName = "steven";
private static final int partitionNumber = 1;
private static final Short replicationFactor = 1;
/**
* 创建AdminClient
*/
public static AdminClient adminClient() {
Properties properties = new Properties();
properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
AdminClient adminClient = AdminClient.create(properties);
return adminClient;
}
/**
* 创建topic
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
AdminClient adminClient = AdminSample.adminClient();
NewTopic newTopic = new NewTopic(topicName, partitionNumber, replicationFactor);
CreateTopicsResult topicsResult = adminClient.createTopics(Arrays.asList(newTopic));
//创建是一个异步过程,但是如果主线程退出了,创建还没执行完就会失败,所以下面的语句是防止主线程退出
topicsResult.all().get();
System.out.println("CreateTopicsResult:" + topicsResult.values());
}
}
2.代码运行结果
CreateTopicsResult:{steven=KafkaFuture{value=null,exception=null,done=true}}