Sunday, July 19, 2020

4 KAFKA TRY: Practice Kafka [ Producer Java -> Single Broker -> Consumer Console ]

4 KAFKA TRY: Practice Kafka [ Producer Java -> Single Broker -> Consumer Console ]


Kafka : Running in Linux m/c (slc15atx.us.oracle.com)

Run Zookeper - bin/zookeeper-server-start.sh config/zookeeper.properties
Run Broker - bin/kafka-server-start.sh config/server.properties
Create topic bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic myfirstTopic1
Run consumer - bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic myfirstTopic1

Producer : Write java in windows eclipse


Create java project - "Kafka_Try_2020"
Add all kafka libraries from -> Kafka\kafka_2.13-2.4.0\libs
Write below java program - "SimpleProducer"
Make sure in code : topic name and Broker Ports are correct

---------------------------------------------------------------------------------------------------

package KafkaCode;

import java.util.Properties;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class SimpleProducer {
 public static void main(String[] args) throws Exception{
        
       String topicName = "myfirstTopic1";
    String key = "Key1";
    String value = "Value-2";
       
       Properties props = new Properties();
       props.put("bootstrap.servers", "slc15atx.us.oracle.com:9092,slc15atx.us.oracle.com:9093");
       props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");         
       props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    Producer<String, String> producer = new KafkaProducer <>(props);
  
    ProducerRecord<String, String> record = new ProducerRecord<>(topicName,key,value);
    producer.send(record);        
       producer.close();
    
    System.out.println("SimpleProducer Completed.");
    }
}


---------------------------------------------------------------------------------------------------































No comments:

Post a Comment