kafka使用入门-api-2

消息发送

	kafka异步发送消息
	使用两个线程,main线程和send线程
	数据流经:拦截器-》序列号器-》分区器

	同步发送
	send方法之后,调用future的get方法阻塞main线程以达到 main线程与send线程串行执行
	要保证消息一定有序需要使用同步发送并且使用一个分区

消息消费

	从头消费有两种情况:组未消费过数据或者组消费保存的offset已经过期
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "101.43.140.67:9092");
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "bigdata1");
        // 组未消费过 或者 组消费过但是消费的数据已经过期删除
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Collections.singletonList("first"));
        while (true) {
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> record : poll) {
                System.out.println(record.key() + ":" + record.value());
            }
			// 异步
            consumer.commitAsync();
        }
posted @ 2022-01-04 10:26  rudynan  阅读(20)  评论(0编辑  收藏  举报