• kafka 消费例子


    package main;
    
    import org.apache.kafka.clients.consumer.*;
    import org.apache.kafka.common.serialization.LongDeserializer;
    import org.apache.kafka.common.serialization.StringDeserializer;
    
    import java.time.Duration;
    import java.util.Collections;
    import java.util.Properties;
    
    public class App {
        public static void main(String[] args) throws Exception {
            System.out.println("开始获取");
            Properties properties = new Properties();
            properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
            properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
            properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
            properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
            properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 10);
            properties.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1);
            properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 1000);
            properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
            Consumer<Long, String> consumer = new KafkaConsumer<Long, String>(properties);
            consumer.subscribe(Collections.singletonList("test"));
            System.out.println("输出");
            while (true) {
                ConsumerRecords<Long, String> records = consumer.poll(Duration.ofSeconds(10));
    
                long lastOffset = 0;
                for (ConsumerRecord<Long, String> record : records) {
                    System.out.printf("
    
    offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
                    lastOffset = record.offset();
                }
                System.out.println("lastOffset read: " + lastOffset);
                Thread.sleep(5);
                // Below call is important to control the offset commit. Do this call after you
                // finish processing the business process.
                consumer.commitSync();
            }
        }
    }
  • 相关阅读:
    Hash表的查找-C语言
    二叉排序树-C语言
    线性表的查找算法-C语言
    拓扑排序和关键路径
    图结构的创建与遍历-C语言
    MySQL数据库基本脚本命令
    哈夫曼树编码-C语言
    协程简述
    Python多线程编程-Threading库
    Python多进程编程-multiprocessing库
  • 原文地址:https://www.cnblogs.com/a-flydog/p/12033871.html
Copyright © 2020-2023  润新知