Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import java.util.Properties;
Import Org.junit.Test;
Import Kafka.consumer.Consumer;
Import Kafka.consumer.ConsumerConfig;
Import Kafka.consumer.ConsumerIterator;
Import Kafka.consumer.KafkaStream;
Import Kafka.javaapi.consumer.ConsumerConnector;
Import Kafka.javaapi.producer.Producer;
Import Kafka.producer.KeyedMessage;
Import Kafka.producer.ProducerConfig;
public class Kafkaproducer {
Private final producer<string, string> Producer;
Public final static String TOPIC = "Test";
Private Kafkaproducer () {
Properties Props = new properties ();
The broker address for Kafka is configured here: List of ports
Props.put ("Metadata.broker.list", "192.168.170.185:9092,192.168.170.185:9093,192.168.170.185:9094");
To configure the serialization class for value
Props.put ("Serializer.class", "Kafka.serializer.StringEncoder");
Configuring the serialization class for key
Props.put ("Key.serializer.class", "Kafka.serializer.StringEncoder");
Request.required.acks
0, which means that the producer never waits for a acknowledgement from the broker (the same behavior as 0.7). This option provides the lowest latency but the weakest durability guarantees (some data would be lost when a server fails) .
1, which means that the producer gets a acknowledgement after the leader replica have received the data. This option provides better durability as the client waits until the server acknowledges the request as successful (only M Essages that were written to the Now-dead leader and not yet replicated would be lost).
-1, which means that the producer gets a acknowledgement after all In-sync replicas has received the data. This option provides the best durability, we guarantee that no messages would be lost as long as at least one in sync repli CA remains.
Props.put ("Request.required.acks", "1");
Producer = new producer<string, string> (new Producerconfig (props));
}
void Produce () {
int Messageno = 1;
Final int COUNT = 101;
int messagecount = 0;
while (Messageno < COUNT) {
String key = String.valueof (Messageno);
String data = "Hello Kafka message:" + key;
Producer.send (New keyedmessage<string, string> (TOPIC, key, data));
SYSTEM.OUT.PRINTLN (data);
Messageno + +;
messagecount++;
}
System.out.println ("producer End produced a" + Messagecount + "Message! ");
}
public static void Main (string[] args)
{
New Kafkaproducer (). produce ();
}
}
Kafka Java API producer