簡體   English   中英

如何在 Java 中以編程方式檢查 Pulsar 主題的存在?

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

當在 Pulsar broker 上禁用自動主題創建時(例如:使用/bin/pulsar-admin namespaces set-auto-topic-creation public/default --disable ),檢查主題的存在並最終檢查可能很有用如果在開始新的消費者訂閱之前丟失,則創建它。

否則,將拋出PulsarClientException$TopicDoesNotExistException

那么,如何在 Java 中檢查主題是否存在並在必要時創建它?

下面的代碼顯示了如何創建一個主題(如果它不存在)。

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;
    }
}

請注意,此處使用的代碼可以在 GitHub 上找到: Cheat Sheet for Apache Pulsar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM