Kafka cluster build and use Java write Kafka producer consumer

Source: Internet
Author: User

Transferred from: http://chengjianxiaoxue.iteye.com/blog/2190488

1 Kafka Cluster Construction

    1The zookeeper cluster was built in 110,111, the            2. Kafka uses 3 node 110,111, theModify configuration file config/server.properties Broker.ID= theHost.name=192.168.1.110Log.dirs=/usr/local/kafka_2.Ten-0.8.2.0/logs replicate to the other two nodes, then modify the config on the corresponding node/Server.pro3. Start, execute bin on three nodes respectively/kafka-server-start.SHConfig/server.properties >/dev/NULL 2>&1&4Create a Theme bin/kafka-topics.SH--create--zookeeper localhost:2181--replication-factor3--partitions3--Topic Test5View topic verbose bin/kafka-topics.SH--describe--zookeeper localhost:2181--Topic Test--topic Test Topic:test partitioncount:3Replicationfactor:3Configs:Topic:test Partition:0Leader: theReplicas: the,111, theIsr: the,111, thetopic:test Partition:1Leader:111Replicas:111, the, theIsr:111, the, thetopic:test Partition:2Leader: theReplicas: the, the,111Isr: the, the,111                  6go to ZK to see the Kafka cluster [zk:localhost:2181(CONNECTED)5]ls/[Admin, zookeeper, consumers, config, controller, ZK-FIFO, Storm, brokers, Controller_epoch] [Zk:localhost:2181(CONNECTED)6]ls/brokers---->View Kafka registered in ZK [topics, IDs] [zk:localhost:2181(CONNECTED)7]ls/brokers/IDs [ the, the,111] [zk:localhost:2181(CONNECTED)8]ls/brokers/ids/ the[ ] [zk:localhost:2181(CONNECTED)9]ls/brokers/topics [Test] [Zk:localhost:2181(CONNECTED)Ten]ls/brokers/topics/test [Partitions] [zk:localhost:2181(CONNECTED) One]ls/brokers/topics/test/partitions [2,1,0] [zk:localhost:2181(CONNECTED) A]


2 Kafka Java Call:

2.1 Java-side production data, Kafka cluster consumption data:

    1 Create Maven project, add the following pom.xml: <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.10</artifactId> <version>0.8.2.0</version> </d      Ependency> 2 Java code: Write data import java.util.Properties to the subject test;            Import Java.util.concurrent.TimeUnit;      Import Kafka.javaapi.producer.Producer;      Import Kafka.producer.KeyedMessage;      Import Kafka.producer.ProducerConfig;                              Import Kafka.serializer.StringEncoder;                    public class Kafkaproducer extends thread{private String topic;              Public kafkaproducer (String topic) {super ();          this.topic = topic;              } @Override public void Run () {Producer Producer = Createproducer ();              int i=0; while (true) {producer.send (new KeyedmeSsage<integer, string> (topic, "message:" + i++));                  try {TimeUnit.SECONDS.sleep (1);                  } catch (Interruptedexception e) {e.printstacktrace (); }}} private Producer Createproducer () {Properties Properties = new Pr              Operties (); Properties.put ("Zookeeper.connect", "192.168.1.110:2181,192.168.1.111:2181,192.168.1.112:2181");//Declaration ZK proper              Ties.put ("Serializer.class", StringEncoder.class.getName ()); Properties.put ("Metadata.broker.list", "192.168.1.110:9092,192.168.1.111:9093,192.168.1.112:9094");//Declaration Kafka           Broker return new Producer<integer, string> (New Producerconfig (properties)); public static void Main (string[] args) {new Kafkaproducer ("Test"). Start ();//               Use the Kafka cluster to create a good theme test}}               3 data for consumption theme test in Kafka cluster: [[email protected] kafka]# bin/kafka-console-consumer.sh--zookeeper loca      lhost:2181--topic Test--from-beginnin 4 start Java code and then look at the data for the cluster consumption as follows: Message:0 message:1       Message:2 message:3 message:4 message:5 message:6 message:7 message:8 message:9      Message:10 message:11 message:12 message:13 message:14 message:15 message:16   Message:17 message:18 message:19 message:20 message:21


3 Kafka use Java to write consumers, so first run Kafkaproducer, run Kafkaconsumer, you can get the data of the producers:

    ImportJava.util.HashMap; Importjava.util.List; ImportJava.util.Map; Importjava.util.Properties; ImportKafka.consumer.Consumer; ImportKafka.consumer.ConsumerConfig; ImportKafka.consumer.ConsumerIterator; ImportKafka.consumer.KafkaStream; ImportKafka.javaapi.consumer.ConsumerConnector; /*** Receive Data * Received: Message:10 Received: Message:11 Received: Message:12 Received: Message:13 Received: Message: *@authorZM **/       Public classKafkaconsumerextendsthread{PrivateString topic;  Publickafkaconsumer (String topic) {Super();  This. Topic =topic; } @Override Public voidrun () {Consumerconnector consumer=Createconsumer (); Map<string, integer> topiccountmap =NewHashmap<string, integer>(); Topiccountmap.put (Topic,1);//get one data from a topic at a timeMap<string, list<kafkastream<byte[],byte[]>>> Messagestreams =Consumer.createmessagestreams (TOPICCOUNTMAP); Kafkastream<byte[],byte[]> stream = Messagestreams.get (topic). get (0);//get the data received each timeconsumeriterator<byte[],byte[]> iterator =Stream.iterator ();  while(Iterator.hasnext ()) {String message=NewString (Iterator.next (). message ()); System.out.println ("Received:" +message); }          }                Privateconsumerconnector Createconsumer () {Properties Properties=NewProperties (); Properties.put ("Zookeeper.connect", "192.168.1.110:2181,192.168.1.111:2181,192.168.1.112:2181");//declaration ZKProperties.put ("Group.id", "group1");//You must use a different group name, and you cannot access topic data within the same group if both the producer and the consumer are in the same group            returnConsumer.createjavaconsumerconnector (NewConsumerconfig (properties)); }                               Public Static voidMain (string[] args) {NewKafkaconsumer ("Test"). Start ();//using the Kafka cluster to create a good theme test                      }                 }  

Kafka cluster build and use Java write Kafka producer consumer

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.