尚硅谷大数据技术之Kafka第4章 Kafka API实战

4.3 Kafka消费者Java API

4.3.1 高级API

0)在控制台创建发送者

[atguigu@hadoop104 kafka]$ bin/kafka-console-producer.sh \

–broker-list hadoop102:9092 –topic first

>hello world

1)创建消费者(过时API)

package com.atguigu.kafka.consume;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import kafka.consumer.Consumer;

import kafka.consumer.ConsumerConfig;

import kafka.consumer.ConsumerIterator;

import kafka.consumer.KafkaStream;

import kafka.javaapi.consumer.ConsumerConnector;

public class CustomConsumer {

@SuppressWarnings(“deprecation”)

public static void main(String[] args) {

Properties properties = new Properties();

properties.put(“zookeeper.connect”, “hadoop102:2181”);

properties.put(“group.id”, “g1”);

properties.put(“zookeeper.session.timeout.ms”, “500”);

properties.put(“zookeeper.sync.time.ms”, “250”);

properties.put(“auto.commit.interval.ms”, “1000”);

// 创建消费者连接器

ConsumerConnector consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(properties));

HashMap<String, Integer> topicCount = new HashMap<>();

topicCount.put(“first”, 1);

Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCount);

KafkaStream<byte[], byte[]> stream = consumerMap.get(“first”).get(0);

ConsumerIterator<byte[], byte[]> it = stream.iterator();

while (it.hasNext()) {

System.out.println(new String(it.next().message()));

}

}

}

2)官方提供案例(自动维护消费情况)(新API)

package com.atguigu.kafka.consume;

import java.util.Arrays;

import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerRecord;

import org.apache.kafka.clients.consumer.ConsumerRecords;

import org.apache.kafka.clients.consumer.KafkaConsumer;

public class CustomNewConsumer {

public static void main(String[] args) {

Properties props = new Properties();

// 定义kakfa 服务的地址,不需要将所有broker指定上

props.put(“bootstrap.servers”, “hadoop102:9092”);

// 制定consumer group

props.put(“group.id”, “test”);

// 是否自动确认offset

props.put(“enable.auto.commit”, “true”);

// 自动确认offset的时间间隔

props.put(“auto.commit.interval.ms”, “1000”);

// key的序列化类

props.put(“key.deserializer”, “org.apache.kafka.common.serialization.StringDeserializer”);

// value的序列化类

props.put(“value.deserializer”, “org.apache.kafka.common.serialization.StringDeserializer”);

// 定义consumer

KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

// 消费者订阅的topic, 可同时订阅多个

consumer.subscribe(Arrays.asList(“first”, “second”,”third”));

while (true) {

// 读取数据,读取超时时间为100ms

ConsumerRecords<String, String> records = consumer.poll(100);

for (ConsumerRecord<String, String> record : records)

System.out.printf(“offset = %d, key = %s, value = %s%n”, record.offset(), record.key(), record.value());

}

}

}


上一篇:
下一篇:
关于尚硅谷
教育理念
名师团队
学员心声
资源下载
视频下载
资料下载
工具下载
加入我们
招聘岗位
岗位介绍
招贤纳师
联系我们
全国统一咨询电话:010-56253825
地址:北京市昌平区宏福科技园综合楼6层(北京校区)

深圳市宝安区西部硅谷大厦B座C区一层(深圳校区)

上海市松江区谷阳北路166号大江商厦6层(上海校区)

武汉市东湖高新开发区东湖网谷(武汉校区)