The below code shows how to create a topic if it does not exist.
public class Example {
private static int DEFAULT_NUM_PARTITIONS = 3;
public static void main(String[] args) throws PulsarClientException, PulsarAdminException {
String topicName = args[0];
PulsarAdmin admin = PulsarAdmin.builder().serviceHttpUrl("http://localhost:8080").build();
if (!topicExists(admin, topicName)) {
System.out.printf("Topic %s does not exist, creating it with %d partitions %n", topicName, DEFAULT_NUM_PARTITIONS);
createTopic(admin, topicName, DEFAULT_NUM_PARTITIONS);
}
// then create consumer/subscription...
}
static void createTopic(final PulsarAdmin admin,
final String topicName,
final int defaultPartitionNum) throws PulsarAdminException {
if (defaultPartitionNum > 0)
admin.topics().createPartitionedTopic(topicName, defaultPartitionNum);
else
admin.topics().createNonPartitionedTopic(topicName);
}
static boolean topicExists(final PulsarAdmin admin,
final String topicName) throws PulsarAdminException {
int partitionNum = admin.topics().getPartitionedTopicMetadata(topicName).partitions;
if (partitionNum == 0) {
try {
admin.topics().getStats(topicName);
} catch (PulsarAdminException.NotFoundException e) {
return false;
}
}
return true;
}
}
Note that the code used here can be found on GitHub: Cheat Sheet for Apache Pulsar