How to check for the existence of a Pulsar topic programmatically in Java?

856 views Asked by At

When auto-topic-creation is disabled on Pulsar brokers (eg: using /bin/pulsar-admin namespaces set-auto-topic-creation public/default --disable), it may be useful to check the existence of the topic and eventually create it if missing before starting a new consumersubscription.

Otherwise, a PulsarClientException$TopicDoesNotExistException will be thrown

So, how to check if a topic exists and create it if necessary in Java ?

1

There are 1 answers

0
fhussonnois On

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