|
| 1 | +package com.baeldung.spring.kafka; |
| 2 | + |
| 3 | +import java.util.concurrent.CountDownLatch; |
| 4 | +import java.util.concurrent.TimeUnit; |
| 5 | + |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; |
| 7 | +import org.springframework.beans.factory.annotation.Value; |
| 8 | +import org.springframework.boot.SpringApplication; |
| 9 | +import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 10 | +import org.springframework.context.ConfigurableApplicationContext; |
| 11 | +import org.springframework.context.annotation.Bean; |
| 12 | +import org.springframework.kafka.annotation.KafkaListener; |
| 13 | +import org.springframework.kafka.core.KafkaTemplate; |
| 14 | + |
| 15 | +@SpringBootApplication |
| 16 | +public class KafkaApplication { |
| 17 | + |
| 18 | + public static void main(String[] args) throws Exception { |
| 19 | + ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args); |
| 20 | + MessageProducer producer = context.getBean(MessageProducer.class); |
| 21 | + producer.sendMessage("Hello, World!"); |
| 22 | + |
| 23 | + MessageListener listener = context.getBean(MessageListener.class); |
| 24 | + listener.latch.await(20, TimeUnit.SECONDS); |
| 25 | + Thread.sleep(60000); |
| 26 | + context.close(); |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + @Bean |
| 31 | + public MessageProducer messageProducer() { |
| 32 | + return new MessageProducer(); |
| 33 | + } |
| 34 | + |
| 35 | + @Bean |
| 36 | + public MessageListener messageListener() { |
| 37 | + return new MessageListener(); |
| 38 | + } |
| 39 | + |
| 40 | + public static class MessageProducer { |
| 41 | + |
| 42 | + @Autowired |
| 43 | + private KafkaTemplate<String, String> kafkaTemplate; |
| 44 | + |
| 45 | + @Value(value = "${message.topic.name}") |
| 46 | + private String topicName; |
| 47 | + |
| 48 | + public void sendMessage(String message) { |
| 49 | + kafkaTemplate.send(topicName, message); |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + public static class MessageListener { |
| 55 | + |
| 56 | + private CountDownLatch latch = new CountDownLatch(2); |
| 57 | + |
| 58 | + @KafkaListener(topics = "${message.topic.name}", group = "foo", containerFactory = "fooKafkaListenerContainerFactory") |
| 59 | + public void listenGroupFoo(String message) { |
| 60 | + System.out.println("Received Messasge in group 'foo': " + message); |
| 61 | + latch.countDown(); |
| 62 | + } |
| 63 | + |
| 64 | + @KafkaListener(topics = "${message.topic.name}", group = "bar", containerFactory = "barKafkaListenerContainerFactory") |
| 65 | + public void listenGroupBar(String message) { |
| 66 | + System.out.println("Received Messasge in group 'bar': " + message); |
| 67 | + latch.countDown(); |
| 68 | + } |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments