Apache Kafka Series (iii) Java API usage

Source: Internet
Author: User

Apache Kafka Series (i) StartApache Kafka Series (ii) command line tools (CLI)Apache Kafka Series (iii) Java API usageSummary:

Apache Kafka Java Client API

First, the basic concept

Kafka integrates the client-side tools for Producer/consumer connection Broker, but in the case of message processing, the two are primarily used for simple server (broker) operations, such as:

1. Create Topic

2. List the existing topic

3. Produce/consume Test for existing topic

Like other messaging systems, Kafka provides a variety of client-side APIs, such as Java,python,ruby,go, that are not implemented in languages. These APIs are great for user-friendly use of Kafka clusters, and this article will demonstrate the use of these APIs

Second, the premise
    • The Kafka 0.11.0 version is installed in the local virtual machine, you can refer to the previous article: Apache Kafka Series (i) Start
    • Locally installed with JDK1.8
    • Idea Compiler
    • Maven3
III. Structure of the project

Maven Pom.xml is as follows:

<Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelversion>4.0.0</modelversion>  <groupId>Com.randy</groupId>  <Artifactid>Kafka_api_demo</Artifactid>  <version>1.0-snapshot</version>  <name>Maven</name>  <Properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <Maven.compiler.source>1.8</Maven.compiler.source>    <Maven.compiler.target>1.8</Maven.compiler.target>  </Properties>  <Dependencies>    <Dependency>      <groupId>Org.apache.kafka</groupId>      <Artifactid>Kafka-clients</Artifactid>      <version>0.11.0.0</version>    </Dependency>  </Dependencies></Project>

Iv. Source Code

  4.1 Producer's source code   

 PackageCom.randy;Importjava.util.Properties;ImportOrg.apache.kafka.clients.producer.KafkaProducer;ImportOrg.apache.kafka.clients.producer.Producer;ImportOrg.apache.kafka.clients.producer.ProducerRecord;/*** Author:randysun * date:2017-08-13 16:23 * Comment:*/ Public classProducerdemo { Public Static voidMain (string[] args) {Properties Properties=NewProperties (); Properties.put ("Bootstrap.servers", "192.168.1.110:9092"); Properties.put ("ACKs", "all"); Properties.put ("Retries", 0); Properties.put ("Batch.size", 16384); Properties.put ("Linger.ms", 1); Properties.put ("Buffer.memory", 33554432); Properties.put ("Key.serializer", "Org.apache.kafka.common.serialization.StringSerializer"); Properties.put ("Value.serializer", "Org.apache.kafka.common.serialization.StringSerializer"); Producer<string, string> producer =NULL; Try{producer=NewKafkaproducer<string, string>(properties);  for(inti = 0; I < 100; i++) {String msg= "Message" +i; Producer.send (NewProducerrecord<string, string> ("HelloWorld", msg)); System.out.println ("Sent:" +msg); }        } Catch(Exception e) {e.printstacktrace (); } finally{producer.close (); }    }}

You can use an instance of the Kafkaproducer class to create a parameter of a Producer,kafkaproducer class that is a series of property values, and then analyze the important attributes that are used:

    • Bootstrap.servers
Properties.put ("Bootstrap.servers", "192.168.1.110:9092");

Bootstrap.servers is the IP address of the Kafka cluster, separated by commas, such as "192.168.1.110:9092,192.168.1.110:9092", if the number of brokers exceeds 1. Among them, 192.168.1.110 is one of my virtual machines

IP address, 9092 is the port you are listening to

    • Key.serializer & Value.serializer
        Properties.put ("Key.serializer", "Org.apache.kafka.common.serialization.StringSerializer");        Properties.put ("Value.serializer", "Org.apache.kafka.common.serialization.StringSerializer");

The serialization type. The Kafka message is sent to the Kafka cluster as a key-value pair, where key is optional and value can be any type. But before the message is sent to the Kafka cluster, producer needs to put different types of

Binary type. This example sends a text message to the Kafka cluster, so the Stringserializer is used.

    • Send a message to the Kafka cluster
    for (int i = 0; i < i++) {      = "Message" + i;      Producer.send (new producerrecord<string, string> ("HelloWorld", msg));      System.out.println ("Sent:" + msg);   

The above code will send 100 messages to HelloWorld this topic

  4.2 Consumer's source code

 PackageCom.randy;Importjava.util.Arrays;Importjava.util.Properties;ImportOrg.apache.kafka.clients.consumer.ConsumerRecord;Importorg.apache.kafka.clients.consumer.ConsumerRecords;ImportOrg.apache.kafka.clients.consumer.KafkaConsumer;/*** Author:randysun * date:2017-08-13 17:06 * Comment:*/ Public classConsumerdemo { Public Static voidMain (string[] args) {Properties Properties=NewProperties (); Properties.put ("Bootstrap.servers", "192.168.1.110:9092"); Properties.put ("Group.id", "Group-1"); Properties.put ("Enable.auto.commit", "true"); Properties.put ("Auto.commit.interval.ms", "1000"); Properties.put ("Auto.offset.reset", "earliest"); Properties.put ("Session.timeout.ms", "30000"); Properties.put ("Key.deserializer", "Org.apache.kafka.common.serialization.StringDeserializer"); Properties.put ("Value.deserializer", "Org.apache.kafka.common.serialization.StringDeserializer"); Kafkaconsumer<string, string> Kafkaconsumer =NewKafkaconsumer<>(properties); Kafkaconsumer.subscribe (Arrays.aslist ("HelloWorld"));  while(true) {consumerrecords<string, string> records = Kafkaconsumer.poll (100);  for(Consumerrecord<string, string>record:records) {System.out.printf ("offset =%d, value =%s", Record.offset (), Record.value ());            System.out.println (); }        }    }}

You can use an instance of the Kafkaconsumer class to create a consumer, the parameters of theKafkaconsumer class are a series of property values, and the following is an analysis of the important attributes used:

    • Bootstrap.servers

As with producer, it is the IP address that points to the Kafka cluster, separated by commas.

    • Group.id

Consumer group ID

    • Key.deserializer and Value.deserializer

Serialization. Consumer deserializes binary messages from the Kafka cluster into the specified type. Because the producer in this example uses the string type, Stringdeserializer is called to deserialize

Consumer subscribed to the message topic is HelloWorld, consumer calls the poll method to round the Kafka cluster message, where parameter 100 is the timeout (consumer waits until there is no message in the Kafka cluster):

        Kafkaconsumer.subscribe (Arrays.aslist ("HelloWorld"));          while (true) {            consumerrecords<string, string> records = Kafkaconsumer.poll (+);              for (consumerrecord<string, string> record:records) {                System.out.printf ("offset =%d, value =%s" c12>, Record.offset (), Record.value ());                System.out.println ();            }        }
V. Summary

This article shows how to create a producer and generate a string type of message that consumer consume these messages. These are based on the Apache Kafka 0.11.0 Java API.

 

Apache Kafka Series (iii) Java API usage

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.