Kafka Java API Consumer

Source: Internet
Author: User

Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import java.util.Properties;

Import Kafka.consumer.ConsumerConfig;
Import Kafka.consumer.ConsumerIterator;
Import Kafka.consumer.KafkaStream;
Import Kafka.javaapi.consumer.ConsumerConnector;
Import Kafka.serializer.StringDecoder;
Import kafka.utils.VerifiableProperties;

public class Kafkaconsumer {

Private final consumerconnector consumer;

Private Kafkaconsumer () {
Properties Props = new properties ();

Zookeeper configuration
Props.put ("Zookeeper.connect", "192.168.170.185:2181");

Consumer group
Props.put ("Group.id", "Testgroup");

ZK Connection timed out
Props.put ("zookeeper.session.timeout.ms", "4000");
Props.put ("zookeeper.sync.time.ms", "200");
Props.put ("auto.commit.interval.ms", "1000");
Props.put ("Auto.offset.reset", "smallest");

Serialization classes
Props.put ("Serializer.class", "Kafka.serializer.StringEncoder");

Consumerconfig config = new Consumerconfig (props);

Consumer = kafka.consumer.Consumer.createJavaConsumerConnector (config);
}

void consume () {
map<string, integer> topiccountmap = new hashmap<string, integer> ();
Topiccountmap.put (Kafkaproducer.topic, New Integer (1));

Stringdecoder Keydecoder = new Stringdecoder (new Verifiableproperties ());
Stringdecoder Valuedecoder = new Stringdecoder (new Verifiableproperties ());

Map<string, list<kafkastream<string, string>>> consumermap =
Consumer.createmessagestreams (Topiccountmap,keydecoder,valuedecoder);
kafkastream<string, string> stream = Consumermap.get (kafkaproducer.topic). Get (0);
Consumeriterator<string, string> it = Stream.iterator ();

int messagecount = 0;
while (It.hasnext ()) {
System.out.println (It.next (). message ());
messagecount++;
if (Messagecount = = 100) {
SYSTEM.OUT.PRINTLN ("Consumer end of the total consumption of" + Messagecount + "Message! ");
}
}
}

public static void Main (string[] args) {
New Kafkaconsumer (). consume ();
}
}

Kafka Java API Consumer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.