Created
May 14, 2015 04:55
-
-
Save piyasde/70af94e8dfc019d8eb58 to your computer and use it in GitHub Desktop.
Sample java client for Apache Kafka Producer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.apt.server; | |
| import kafka.producer.KeyedMessage; | |
| import kafka.producer.ProducerConfig; | |
| import java.util.Properties; | |
| public class KafkaProducer extends Thread | |
| { | |
| private final kafka.javaapi.producer.Producer<Integer, String> producer; | |
| private final String topic; | |
| private final Properties props = new Properties(); | |
| public KafkaProducer(String topic) | |
| { | |
| props.put("serializer.class", "kafka.serializer.StringEncoder"); | |
| props.put("metadata.broker.list", "localhost:9092"); | |
| props.put("zk.connect", "localhost:2181"); | |
| // Use random partitioner. Don't need the key type. Just set it to Integer. | |
| // The message is of type String. | |
| producer = new kafka.javaapi.producer.Producer<Integer, String>(new ProducerConfig(props)); | |
| this.topic = topic; | |
| } | |
| public void run() { | |
| int messageNo = 1; | |
| while(true) | |
| { | |
| String messageStr = new String("Message_" + messageNo); | |
| KeyedMessage<Integer, String> km = new KeyedMessage<Integer, String>(this.topic, messageStr); | |
| try { | |
| sleep(2000); | |
| } catch (InterruptedException e) { | |
| // TODO Auto-generated catch block | |
| e.printStackTrace(); | |
| } | |
| producer.send(km); | |
| messageNo++; | |
| } | |
| } | |
| public static void main(String[] args) { | |
| (new KafkaProducer("test")).start(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment