Created
February 1, 2022 13:27
-
-
Save mmafrar/8967f9d8ae8cbc491edfaeae60691a0c to your computer and use it in GitHub Desktop.
Getting Started with Apache Kafka and Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.kafka; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.WebApplicationType; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.kafka.config.KafkaListenerEndpointRegistry; | |
import org.springframework.kafka.listener.MessageListenerContainer; | |
@SpringBootApplication | |
public class SpringBootWithKafkaApplication { | |
private final Producer producer; | |
@Autowired | |
private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry; | |
@Autowired | |
SpringBootWithKafkaApplication(Producer producer) { | |
this.producer = producer; | |
} | |
public static void main(String[] args) { | |
SpringApplication application = new SpringApplication(SpringBootWithKafkaApplication.class); | |
application.setWebApplicationType(WebApplicationType.NONE); | |
application.run(args); | |
} | |
@Bean | |
public CommandLineRunner CommandLineRunnerBean() { | |
return (args) -> { | |
for (String arg : args) { | |
switch (arg) { | |
case "--producer": | |
this.producer.sendMessage("awalther", "t-shirts"); | |
this.producer.sendMessage("htanaka", "t-shirts"); | |
this.producer.sendMessage("htanaka", "batteries"); | |
this.producer.sendMessage("eabara", "t-shirts"); | |
this.producer.sendMessage("htanaka", "t-shirts"); | |
this.producer.sendMessage("jsmith", "book"); | |
this.producer.sendMessage("awalther", "t-shirts"); | |
this.producer.sendMessage("jsmith", "batteries"); | |
this.producer.sendMessage("jsmith", "gift card"); | |
this.producer.sendMessage("eabara", "t-shirts"); | |
break; | |
case "--consumer": | |
MessageListenerContainer listenerContainer = kafkaListenerEndpointRegistry.getListenerContainer("myConsumer"); | |
listenerContainer.start(); | |
break; | |
default: | |
break; | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment