Kafka with Spring Boot

Dependencies

  • spring-kafka : For Spring Kafka support

  • kafka-clients : For Kafka client support

Configuration

  • Configure Kafka broker URL and port in application.properties:

spring.kafka.bootstrap-servers=<kafka-broker-url>:<port>

Producer Configuration

  • Use KafkaTemplate to send messages to Kafka topics

  • Create a KafkaTemplate bean:

@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
    return new KafkaTemplate<>(producerFactory());
}
  • Define a ProducerFactory bean:

@Bean
public ProducerFactory<String, String> producerFactory() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return new DefaultKafkaProducerFactory<>(configProps);
}
  • Use KafkaTemplate to send messages to Kafka topics:

Consumer Configuration

  • Create a KafkaListenerContainerFactory bean:

  • Define a ConsumerFactory bean:

  • Use @KafkaListener annotation to consume messages from Kafka topics:

Last updated

Was this helpful?