producersImport java.util.Properties;
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;
Construction method
Public kafkaproducer (String topic) {
this.topic = topic;
}
@Override
public void Run () {
Producer<integer, string> Producer = Createproducer ();
for (int i =1; i<=10;i++) {
String message = "message" +I;
Producer.send (New Keyedmessage<integer, string> (topic, message));
System.out.println ("producer-generated---------->" +message);
try {
Sleep 1S
Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Public Producer Createproducer () {
Properties Properties = new properties ();
Properties.setproperty ("Zookeeper.connect", "192.168.80.20:2181,192.168.80.21:2181,192.168.80.22:2181");
// Properties.setproperty ("Zookeeper.connect", "cloud1:2181,cloud2:2181,cloud3:2181");
Properties.setproperty ("Serializer.class", StringEncoder.class.getName ());
Properties.setproperty ("Serializer.class", "Kafka.serializer.StringEncoder");
Properties.setproperty ("Metadata.broker.list", "192.168.80.20:9092");
return new Producer<integer, string> (New Producerconfig (properties));
}
public static void Main (string[] args) {
New Kafkaproducer ("Test"). Start ();
}
}
ConsumerImport Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import java.util.Properties;
Import Kafka.consumer.Consumer;
Import Kafka.consumer.ConsumerConfig;
Import Kafka.consumer.ConsumerIterator;
Import Kafka.consumer.KafkaStream;
Import Kafka.javaapi.consumer.ConsumerConnector;
public class Kafkacomsumer extends Thread {
Private String topic;
Public Kafkacomsumer (String topic) {
this.topic = topic;
}
@Override
public void Run () {
Consumerconnector consumer = Createconsumer ();
map<string, integer> topiccountmap = new hashmap<string, integer> ();
Topiccountmap.put (topic, 1);
Map<string, list<kafkastream<byte[], byte[]>>> messagestreams = Consumer.createmessagestreams ( TOPICCOUNTMAP);
Kafkastream<byte[], byte[]> kafkastream = messagestreams.get (topic). get (0);
Consumeriterator<byte[], byte[]> iterator = Kafkastream.iterator ();
while (Iterator.hasnext ()) {
String message = new String (Iterator.next (). message ());
System.out.println ("Received information------------" "+message");
}
}
Public Consumerconnector Createconsumer () {
Properties Properties = new properties ();
Properties.setproperty ("Zookeeper.connect", "192.168.80.20:2181,192.168.80.21:2181,192.168.80.22:2181");
Properties.setproperty ("Group.id", "group1");
Return Consumer.createjavaconsumerconnector (New Consumerconfig (properties));
}
public static void Main (string[] args) {
New Kafkacomsumer ("Test"). Start ();
}
}
Kafka Producer Consumer API interface