Support Questions
Find answers, ask questions, and share your expertise
Announcements
Alert: Welcome to the Unified Cloudera Community. Former HCC members be sure to read and learn how to activate your account here.

KAFKA StringSerializer question

Highlighted

KAFKA StringSerializer question

Master Collaborator

the following java code is working for me and it posts a message to Kafka if I assign any string to the "value" variable.

my question is how can I pass JSON object to "value " ?

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
/**
 * An example using the new java client Producer for Kafka 0.8.2
 *
 * 2015/02/27
 * @author Cameron Gregory, http://www.bloke.com/
 */
public class TestProducer {
        public static void main(String args[]) throws InterruptedException, ExecutionException {
                Properties props = new Properties();
                props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"myserver:6667");
                props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
                props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
                KafkaProducer<String,String> producer = new KafkaProducer<String,String>(props);
                boolean sync = false;
                String topic="kafkatopic";
                String key = "mykey";
                String value = ".. needs to input JSON here ";
                ProducerRecord<String,String> producerRecord = new ProducerRecord<String,String>(topic, key, value);
                if (sync) {
                        producer.send(producerRecord).get();
                } else {
                        producer.send(producerRecord);
                }
                producer.close();
        }
}