设为首页 收藏本站
查看: 760|回复: 0

[经验分享] 【Kafka十三】Kafka Simple Consumer

[复制链接]

尚未签到

发表于 2017-5-23 15:08:26 | 显示全部楼层 |阅读模式
  代码中关于Host和Port是割裂开的,这会导致单机环境下的伪分布式Kafka集群环境下,这个例子没法运行。
  实际情况是需要将host和port绑定到一起,

package kafka.examples.lowlevel;
import kafka.api.FetchRequest;
import kafka.api.FetchRequestBuilder;
import kafka.api.PartitionOffsetRequestInfo;
import kafka.common.ErrorMapping;
import kafka.common.TopicAndPartition;
import kafka.javaapi.*;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.message.MessageAndOffset;
import java.nio.ByteBuffer;
import java.util.*;
public class KafkaLowLevelConsumer {
//参数说明:
/*
Maximum number of messages to read (so we don’t loop forever)
Topic to read from
Partition to read from
One broker to use for Metadata lookup
Port the brokers listen on
*/
public static void main(String args[]) {
KafkaLowLevelConsumer consumer = new KafkaLowLevelConsumer();
//读取的消息数
long maxReads = Long.parseLong(args[0]);
//读取的topic名称
String topic = args[1];
//读取的partition,从0开始的
int partition = Integer.parseInt(args[2]);

List<String> seeds = new ArrayList<String>();
seeds.add(args[3]);
//seed broker的监听端口,每个Topic和Partition的信息是存放于zk目录:/brokers/topics/learn.topic.p8.r2
int port = Integer.parseInt(args[4]);
try {
consumer.run(maxReads, topic, partition, seeds, port);
} catch (Exception e) {
System.out.println("Oops:" + e);
e.printStackTrace();
}
}
private List<String> replicaBrokers = new ArrayList<String>();
public KafkaLowLevelConsumer() {
replicaBrokers = new ArrayList<String>();
}
public void run(long maxReads, String topic, int partition, List<String> seedBrokers, int port) throws Exception {
//获取指定topic和partition的元信息,PartitionMetadata的leader和replicas方法返回leader和replicas brokers
PartitionMetadata metadata = findLeader(seedBrokers, port, topic, partition);
if (metadata == null) {
System.out.println("Can't find metadata for Topic and Partition. Exiting");
return;
}
//获取lead partition所在的broker
if (metadata.leader() == null) {
System.out.println("Can't find Leader for Topic and Partition. Exiting");
return;
}
//获取leader broker的host信息,不包括端口信息
String leadBroker = metadata.leader().host();
String clientName = "Client_" + topic + "_" + partition;
//构造SimpleConsumer,为什么port和leaderBroker不一致?
//这里的leadBroker, port是配对的,应该是metadata.leader().port()
SimpleConsumer consumer = new SimpleConsumer(leadBroker, port, 100000, 64 * 1024, clientName);

//获取读取的offset
long readOffset = getLastOffset(consumer, topic, partition, kafka.api.OffsetRequest.EarliestTime(), clientName);
int numErrors = 0;
while (maxReads > 0) {
if (consumer == null) {
consumer = new SimpleConsumer(leadBroker, port, 100000, 64 * 1024, clientName);
}
FetchRequest req = new FetchRequestBuilder()
.clientId(clientName)
.addFetch(topic, partition, readOffset, 100000) // Note: this fetchSize of 100000 might need to be increased if large batches are written to Kafka
.build();
FetchResponse fetchResponse = consumer.fetch(req);
//Since the SimpleConsumer doesn't handle lead Broker failures, you have to write a bit of code to handle it.
if (fetchResponse.hasError()) {
numErrors++;
// Something went wrong!
short code = fetchResponse.errorCode(topic, partition);
System.out.println("Error fetching data from the Broker:" + leadBroker + " Reason: " + code);
if (numErrors > 5) break;
if (code == ErrorMapping.OffsetOutOfRangeCode()) {
// We asked for an invalid offset. For simple case ask for the last element to reset
readOffset = getLastOffset(consumer, topic, partition, kafka.api.OffsetRequest.LatestTime(), clientName);
continue;
}
consumer.close();
consumer = null;
leadBroker = findNewLeader(leadBroker, topic, partition, port);
continue;
}
numErrors = 0;
long numRead = 0;
for (MessageAndOffset messageAndOffset : fetchResponse.messageSet(topic, partition)) {
long currentOffset = messageAndOffset.offset();
if (currentOffset < readOffset) {
System.out.println("Found an old offset: " + currentOffset + " Expecting: " + readOffset);
continue;
}
readOffset = messageAndOffset.nextOffset();
ByteBuffer payload = messageAndOffset.message().payload();
byte[] bytes = new byte[payload.limit()];
payload.get(bytes);
System.out.println(String.valueOf(messageAndOffset.offset()) + ": " + new String(bytes, "UTF-8"));
numRead++;
maxReads--;
}
//This method uses the findLeader() logic we defined earlier to find the new leader,
// except here we only try to connect to one of the replicas for the topic/partition.
// This way if we can’t reach any of the Brokers with the data we are interested in we give up and exit hard.
//Since it may take a short time for ZooKeeper to detect the leader loss and assign a new leader, we sleep if we don’t get an answer.
// In reality ZooKeeper often does the failover very quickly so you never sleep
if (numRead == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
if (consumer != null) consumer.close();
}
// Finding Starting Offset for Reads
// Now define where to start reading data. Kafka includes two constants to help,
// kafka.api.OffsetRequest.EarliestTime() finds the beginning of the data in the logs and starts streaming from there,
// kafka.api.OffsetRequest.LatestTime() will only stream new messages.
// Don’t assume that offset 0 is the beginning offset, since messages age out of the log over time.
public static long getLastOffset(SimpleConsumer consumer, String topic, int partition,
long whichTime, String clientName) {
TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition);
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(whichTime, 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), clientName);
//Get a list of valid offsets (up to maxSize) before the given time.
OffsetResponse response = consumer.getOffsetsBefore(request);
if (response.hasError()) {
System.out.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition));
return 0;
}
long[] offsets = response.offsets(topic, partition);
return offsets[0];
}
//Since the SimpleConsumer doesn't handle lead Broker failures, you have to write a bit of code to handle it.
//Here, once the fetch returns an error, we log the reason, close the consumer then try to figure out who the new leader is.
private String findNewLeader(String oldLeader, String topic, int partition, int port) throws Exception {
for (int i = 0; i < 3; i++) {
boolean goToSleep;
PartitionMetadata metadata = findLeader(replicaBrokers, port, topic, partition);
if (metadata == null) {
goToSleep = true;
} else if (metadata.leader() == null) {
goToSleep = true;
} else if (oldLeader.equalsIgnoreCase(metadata.leader().host()) && i == 0) {
// first time through if the leader hasn't changed give ZooKeeper a second to recover
// second time, assume the broker did recover before failover, or it was a non-Broker issue
//
goToSleep = true;
} else {
return metadata.leader().host();
}
if (goToSleep) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
System.out.println("Unable to find new leader after Broker failure. Exiting");
throw new Exception("Unable to find new leader after Broker failure. Exiting");
}
///根据指定的Broker,查找指定topic和partition的Lead Partition
//Finding the Lead Broker for a Topic and Partition
//The easiest way to do this is to pass in a set of known Brokers to your logic,
// either via a properties file or the command line.
// These don’t have to be all the Brokers in the cluster,
// rather just a set where you can start looking for a live Broker to query for Leader information.
//seedBrokers是使用的replicaBrokers列表
//调用PartitionMetadata的leader和replicas方法可以得到该Partition对应的Leader和Replicas Broker信息
private PartitionMetadata findLeader(List<String> seedBrokers, int port, String topic, int partition) {
PartitionMetadata returnMetaData = null;
loop:
for (String seed : seedBrokers) {
SimpleConsumer consumer = null;
try {
/**
class SimpleConsumer(val host: String,
val port: Int,
val soTimeout: Int,
val bufferSize: Int,
val clientId: String)
*/
consumer = new SimpleConsumer(seed, port, 100000, 64 * 1024, "leaderLookup");
List<String> topics = Collections.singletonList(topic);
TopicMetadataRequest req = new TopicMetadataRequest(topics);
kafka.javaapi.TopicMetadataResponse resp = consumer.send(req);
//The call to topicsMetadata() asks the Broker you are connected to for all the details about the topic we are interested in
List<TopicMetadata> metaData = resp.topicsMetadata();
for (TopicMetadata item : metaData) {
//The loop on partitionsMetadata iterates through all the partitions until we find the one we want. Once we find it, we can break out of all the loops.
for (PartitionMetadata part : item.partitionsMetadata()) {
if (part.partitionId() == partition) {
returnMetaData = part;
break loop;
}
}
}
} catch (Exception e) {
System.out.println("Error communicating with Broker [" + seed + "] to find Leader for [" + topic
+ ", " + partition + "] Reason: " + e);
} finally {
if (consumer != null) consumer.close();
}
}
if (returnMetaData != null) {
replicaBrokers.clear();
///将replicaBrokers进行缓存
for (kafka.cluster.Broker replica : returnMetaData.replicas()) {
replicaBrokers.add(replica.host());
}
}
return returnMetaData;
}
}

  参考:https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+SimpleConsumer+Example

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-379790-1-1.html 上篇帖子: kafka详解一、Kafka简介 下篇帖子: kafka自启动脚本
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表