Sample Java Producer
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
public class SampleProducer {
// Set the stream and topic to publish to.
public static String topic = "/<path to and name of the stream>:<name of topic>";
// Set the number of messages to send.
public static int numMessages = 50;
// Declare a new producer.
public static KafkaProducer<Integer, String> producer;
public static void main(String[] args) {
configureProducer();
for(int i = 0; i < numMessages; i++) {
// Set content of each message.
String messageText = "Msg " + i;
/* Add each message to a record. A ProducerRecord object
identifies the topic or specific partition to publish
a message to. */
ProducerRecord<Integer, String> rec = new ProducerRecord(topic, i, messageText);
// Send the record to the producer client library.
producer.send(rec);
System.out.println("Sent message number " + i);
}
producer.close();
System.out.println("All done.");
}
/* Set the value for a configuration parameter.
This configuration parameter specifies which class
to use to serialize the value of each message. */
public static void configureProducer() {
Properties props = new Properties();
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.IntegerSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringSerializer");
producer = new KafkaProducer(props);
}
}
For additional information, see https://github.com/mapr-demos/mapr-streams-sample-programs.