SpringBoot整合Kafka

1 篇文章 0 订阅
1 篇文章 0 订阅

SpringBoot整合Kafka

一、添加kafka依赖

 <dependency>
             <groupId>org.apache.kafka</groupId>
             <artifactId>kafka-clients</artifactId>
             <version>2.4.0</version>
</dependency>

二、获取topic列表

/**
     * 获取kafka中topic列表
     * @param kafkaConnect kafka连接地址
     * @return long topic中消息总量
     * @Time 2022-11-09 15:37:10
     */
public static List<String> getKafkaTopicList(String kafkaConnect) throws ExecutionException, InterruptedException {
        Properties properties = new Properties();
        properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConnect);
        AdminClient adminClient = AdminClient.create(properties);
        ListTopicsResult listTopicsResult = adminClient.listTopics();
        Set<String> strings = listTopicsResult.names().get();
        List<String> topicList = new ArrayList<>();
        for (String topicName : strings) {
            topicList.add(topicName);
        }
        return topicList;
    }

三、通过每个topic名称获取每隔topic下面的消息总量

/**
     * 根据topic名称计算topic消息总量
     * @param topicName kafka中topic名称
     * @param kafkaConnect kafka连接地址
     * @return long topic中消息总量
     * @Time 2022-11-09 15:45:32
     */
    public static long getKafkaTopicMessageTotal(String topicName,String kafkaConnect) {
        Properties props = new Properties();
        props.put("bootstrap.servers", kafkaConnect);
        props.put("group.id", topicName);
        props.put("enable.auto.commit", "false");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer1 = new KafkaConsumer<>(props);

        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            List<TopicPartition> tps = Optional.ofNullable(consumer.partitionsFor(topicName))
                    .orElse(Collections.<PartitionInfo>emptyList())
                    .stream()
                    .map(info -> new TopicPartition(info.topic(), info.partition()))
                    .collect(Collectors.toList());
            Map<TopicPartition, Long> beginOffsets = consumer.beginningOffsets(tps);
            Map<TopicPartition, Long> endOffsets = consumer.endOffsets(tps);
            return tps.stream().mapToLong(tp -> endOffsets.get(tp) - beginOffsets.get(tp)).sum();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值