• kafka的Java客户端-消费者


    kafka的Java客户端-消费者

    一、kafka消费方式

    • pull(拉)模式:consumer采用从broker中主动拉取数据。Kafka 采用这种方式
    • push(推)模式:Kafka没有采用这种方式,因为由broker决定消息发送速率,很难适应所有消费者的消费速率

    二、消费者原理

    Consumer Group(CG):消费者组,由多个consumer组成。形成一个消费者组的条件,是所有消费者的groupid相同

    • 消费者组内每个消费者负责消费不同分区的数据,一个分区只能由一个组内消费者消费
    • 消费者组之间互不影响。所有的消费者都属于某个消费者组,即消费者组是逻辑上的一个订阅者

    在这里插入图片描述

    在这里插入图片描述

    消费者组消费流程

    在这里插入图片描述

    三、消费者重要参数

    参数名称描述
    bootstrap.servers向 Kafka集群建立初始连接用到的 host/port列表
    key.deserializer 和value.deserializer指定接收消息的 key 和 value 的反序列化类型。一定要写全类名
    group.id标记消费者所属的消费者组
    enable.auto.commit默认值为 true,消费者会自动周期性地向服务器提交偏移量
    auto.commit.interval.ms如果设置了 enable.auto.commit 的值为 true, 则该值定义了消费者偏移量向 Kafka提交的频率,默认 5s
    auto.offset.reset当 Kafka 中没有初始偏移量或当前偏移量在服务器中不存在(如,数据被删除了),该如何处理? earliest:自动重置偏移量到最早的偏移量。 latest:默认,自动重置偏移量为最新的偏移量。 none:如果消费组原来的(previous)偏移量不存在,则向消费者抛异常。 anything:向消费者抛异常
    offsets.topic.num.partitions__consumer_offsets 的分区数,默认是 50 个分区
    heartbeat.interval.msKafka 消费者和 coordinator 之间的心跳时间,默认 3s。该条目的值必须小于 session.timeout.ms ,也不应该高于session.timeout.ms 的 1/3
    session.timeout.msKafka 消费者和 coordinator 之间连接超时时间,默认 45s。超过该值,该消费者被移除,消费者组执行再平衡
    max.poll.interval.ms消费者处理消息的最大时长,默认是 5 分钟。超过该值,该消费者被移除,消费者组执行再平衡
    fetch.min.bytes默认 1 个字节。消费者获取服务器端一批消息最小的字节数
    fetch.max.wait.ms默认 500ms。如果没有从服务器端获取到一批数据的最小字节数。该时间到,仍然会返回数据
    fetch.max.bytes默认 Default: 52428800(50 m)。消费者获取服务器端一批消息最大的字节数。如果服务器端一批次的数据大于该值(50m)仍然可以拉取回来这批数据,因此,这不是一个绝对最大值。一批次的大小受 message.max.bytes (brokerconfig)or max.message.bytes (topic config)影响
    max.poll.records一次 poll拉取数据返回消息的最大条数,默认是 500 条

    四、消费者API

    独立消费者案例-订阅主题

    在这里插入图片描述

    public class CustomConsumer {
    
        public static void main(String[] args) {
    
            // 1.创建消费者的配置对象
            Properties properties = new Properties();
    
            // 2.给消费者配置对象添加参数
            properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"1.14.252.45:19092,1.14.252.45:19093,1.14.252.45:19094");
            //显示设置偏移量自动提交
            properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);
            //设置偏移量提交时间间隔
            properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,1000);
            // 3.配置序列化 必须
            properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
            properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    
            // 4.配置消费者组(组名任意起名) 必须
            properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
    
    //        // 设置分区分配策略
    //        properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,"org.apache.kafka.clients.consumer.StickyAssignor");
    
            // 创建消费者对象
            KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
    
            // 注册要消费的主题(可以消费多个主题)
            kafkaConsumer.subscribe(Collections.singletonList("first"));
    
            // 拉取数据打印
            while (true) {
                // 设置 1s 中消费一批数据
                ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1));
                // 打印消费到的数据
                for (ConsumerRecord<String, String> record : consumerRecords) {
                    System.out.printf("收到消息:partition = %d,offset = %d, key =%s, value = %s%n", record.partition(),record.offset(), record.key(), record.value());
                }
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述

    在这里插入图片描述

    独立消费者案例-订阅分区

    在这里插入图片描述

    public class CustomConsumerPartition {
    
        public static void main(String[] args) {
            // 1.创建消费者的配置对象
            Properties properties = new Properties();
    
            // 2.给消费者配置对象添加参数
            properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"1.14.252.45:19092,1.14.252.45:19093,1.14.252.45:19094");
            //显示设置偏移量自动提交
            properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);
            //设置偏移量提交时间间隔
            properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,1000);
            // 3.配置序列化 必须
            properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
            properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    
            // 4.配置消费者组(组名任意起名) 必须
            properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
    
            // 创建消费者对象
            KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
    
            // 订阅主题对应的分区
            ArrayList<TopicPartition> topicPartitions = new ArrayList<>();
            topicPartitions.add(new TopicPartition("first",0));
            kafkaConsumer.assign(topicPartitions);
    
            // 拉取数据打印
            while (true) {
                // 设置 1s 中消费一批数据
                ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1));
                // 打印消费到的数据
                for (ConsumerRecord<String, String> record : consumerRecords) {
                    System.out.printf("收到消息:partition = %d,offset = %d, key =%s, value = %s%n", record.partition(),record.offset(), record.key(), record.value());
                }
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    在这里插入图片描述

    消费者组案例

    在这里插入图片描述

    复制一份CustomConsumer的代码,取名为CustomConsumer1,同时运行这俩个代码

    public class CustomConsumer {
    
        public static void main(String[] args) {
    
            // 1.创建消费者的配置对象
            Properties properties = new Properties();
    
            // 2.给消费者配置对象添加参数
            properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"1.14.252.45:19092,1.14.252.45:19093,1.14.252.45:19094");
            //显示设置偏移量自动提交
            properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,true);
            //设置偏移量提交时间间隔
            properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,1000);
            // 3.配置序列化 必须
            properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
            properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    
            // 4.配置消费者组(组名任意起名) 必须
            properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
    
    //        // 设置分区分配策略
    //        properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,"org.apache.kafka.clients.consumer.StickyAssignor");
    
            // 创建消费者对象
            KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
    
            // 注册要消费的主题(可以消费多个主题)
            kafkaConsumer.subscribe(Collections.singletonList("first"));
    
            // 拉取数据打印
            while (true) {
                // 设置 1s 中消费一批数据
                ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1));
                // 打印消费到的数据
                for (ConsumerRecord<String, String> record : consumerRecords) {
                    System.out.printf("收到消息:partition = %d,offset = %d, key =%s, value = %s%n", record.partition(),record.offset(), record.key(), record.value());
                }
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    然后启动生产者代码

    public class MyProducer2 {
        public static void main(String[] args){
    
            //1.创建kafka生产者配置对象
            Properties props = new Properties();
            //2.给 kafka 配置对象添加配置信息:bootstrap.servers
            props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "1.14.252.45:19092,1.14.252.45:19093,1.14.252.45:19094");
            //key,value 序列化(必须)
            //把发送的key从字符串序列化为字节数组
            props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            //把发送消息value从字符串序列化为字节数组
            props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            // 3. 创建 kafka 生产者对象
            Producer<String, String> producer = new KafkaProducer<>(props);
            for (int i = 0; i < 5; i++) {
                Order order = new Order((long) i, 100);
                ProducerRecord<String, String> producerRecord = new ProducerRecord<>("first", order.getId().toString(), JSON.toJSONString(order));
                //4. 调用 send 方法,发送消息
                producer.send(producerRecord, (metadata, exception) -> {
                    if (exception != null) {
                        System.err.println("发送消息失败:" + Arrays.toString(exception.getStackTrace()));
                    }
                    if (metadata != null) {
                        System.out.println("异步方式发送消息结果:" + "topic-" + metadata.topic() + "|partition-" + metadata.partition() + "|offset-" + metadata.offset());
                    }
                });
            }
            producer.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述

    重新发送到一个全新的主题中,由于默认创建的主题分区数为 1,可以看到只能有一个消费者消费到数据

  • 相关阅读:
    【英语:发音基础】A6.基础词汇-核心形容词
    机器学习算法:支持向量机(SVM)
    resubmit 渐进式防重复提交框架简介
    【Web】Java反序列化之CC6--HashMap版
    Java Math.acos()方法具有什么功能呢?
    YOLOv5 分类模型 数据集加载 1
    高性能分布式对象存储——MinIO(环境部署)
    ppt技能提升
    flutter播放rtmp视频
    01. 信息搜集:Web 1~10
  • 原文地址:https://blog.csdn.net/weixin_43296313/article/details/125525541