• 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();
            }
        }
    }
  • 相关阅读:
    reStructuredText学习
    PYTHON编码处理-str与Unicode的区别
    如何参与一个GitHub开源项目?
    Boost库编译安装
    git push失败the remote end hung up unexpectedly
    VBox虚拟机安装debian
    debian设置英文模式
    python 使用json.dumps() 的indent 参数添加缩进空格数,格式化字符串后输出
    unittest之装饰器 @classmethod
    jmeter正则提取信息头数据
  • 原文地址:https://www.cnblogs.com/a-flydog/p/12033871.html
Copyright © 2020-2023  润新知