consumer:
public String getKafkaInfo() {
String bootstrapserver = "******:9092";
String mygroupID = "demo";
//consumer properties
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapserver);
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG,TOPIC);
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
//create consumer
KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);
//subsrcribe consumer
consumer.subscribe(Arrays.asList(TOPIC));
//poll for new_data
ConsumerRecords<String,String > records = consumer.poll(1000);
for (ConsumerRecord<String,String > record : records){
log.info("Key : " + record.key() + "Value : " + record.value());
log.info("Partition " + record.partition() + "Offset : " + record.offset());
}
return "a";
}
producer:
public static Future<RecordMetadata> sendKafkaMsg(ProducerRecord<String, String> record) {
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, CONFIG_IP_AND_PORT);
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(p);
Future<RecordMetadata> kafkaRes;
try {
kafkaRes = kafkaProducer.send(record);
} finally {
kafkaProducer.close();
}
//kafkaRes = kafkaProducer.send(record);
return kafkaRes;
}