BAEL-4609 - Testing Kafka and Spring Boot (#10249)
* BAEL-4437 - System Rules * BAEL-4687 Testing Kafka and Spring Boot * BAEL-4609 - Testing Kafka and Spring Boot Co-authored-by: Jonathan Cook <jcook@sciops.esa.int>
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.kafka.embedded;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Component
|
||||
public class KafkaConsumer {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaConsumer.class);
|
||||
|
||||
private CountDownLatch latch = new CountDownLatch(1);
|
||||
private String payload = null;
|
||||
|
||||
@KafkaListener(topics = "${test.topic}")
|
||||
public void receive(ConsumerRecord<?, ?> consumerRecord) {
|
||||
LOGGER.info("received payload='{}'", consumerRecord.toString());
|
||||
setPayload(consumerRecord.toString());
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
public CountDownLatch getLatch() {
|
||||
return latch;
|
||||
}
|
||||
|
||||
public String getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
private void setPayload(String payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.kafka.embedded;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class KafkaProducer {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaProducer.class);
|
||||
|
||||
@Autowired
|
||||
private KafkaTemplate<String, String> kafkaTemplate;
|
||||
|
||||
public void send(String topic, String payload) {
|
||||
LOGGER.info("sending payload='{}' to topic='{}'", payload, topic);
|
||||
kafkaTemplate.send(topic, payload);
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.kafka.embedded;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableAutoConfiguration
|
||||
public class KafkaProducerConsumerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(KafkaProducerConsumerApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user