-
Kafka Demo Version : 0.8.2.2
-
Kafka消费工具类(低阶API)
项目背景:
数据质量平台需对Topic中的数据进行抽样,为避免申请GroupId流程,同时减轻Zk压力,使用Low-Level Kafka Client进行消费
功能介绍:
* 本例作为项目预研demo
* 指定Topic和Partition(partition=0),查询此分区的最小/最大offset
* 根据采样算法,消费数据
使用SimpleConsumer的步骤
* 明确要消费的Topic及其Partition,确定分区信息(PartitionMetadata对象)
* 找到待消费Partition所在的Broker Leader
* 构建业务上要求的数据请求(FetchRequest)
* 获取(fetch)数据
* 针对当leader发生变更的情况,恢复消费
说明:demo中的数据抽样操作 并不是 高频操作,并且 抽样结束 即可结束动作,所以 此处 并没有 针对leader发生变更的情况恢复消费操作。
DEMO
Sampling:
/**
* Kafka数据采样,针对topic的某个partition数据进行采样
*/
public class Sampling implements Runnable {
private final int SO_TIMEOUT = 10_000;
private final int BUFFER_SIZE = 64 * 1024;
private final int FETCH_SIZE = 1024;
private final List<String> BROKERS;
private final int PORT;
private final String TOPIC;
private final int PARTITION;
private final TaskInterface TASK;
public Sampling(List<String> brokers, int port, String topic, int partition, TaskInterface task) {
this.BROKERS = brokers;
this.PORT = port;
this.TOPIC = topic;
this.PARTITION = partition;
this.TASK = task;
}