Important Notice: CloudKarafka is shutting down. Read all about it in our End of Life Announcement

Spring Boot

Spring Boot has very nice integration to Apache Kafka using the library spring-kafka which wraps the Kafka Java client and gives you a simple yet powerful integration.

CloudKarafka uses SASL/SCRAM for authentication, there is out-of-the-box support for this with spring-kafka you just have to set the properties in the application.properties file.

Example:

spring.kafka.bootstrap-servers=test-speedcar-01.srvs.cloudkafka.com:9094
spring.kafka.properties.security.protocol=SASL_SSL
spring.kafka.properties.sasl.mechanism=SCRAM-SHA-256
spring.kafka.properties.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="USERNAME" password="PASSWORD";

Consumer example in Spring

class Consumer {
    @KafkaListener(topics = "test-topic")
    public void processMessage(String message,
                               @Header(KafkaHeaders.RECEIVED_PARTITION_ID) List partitions,
                               @Header(KafkaHeaders.RECEIVED_TOPIC) List topics,
                               @Header(KafkaHeaders.OFFSET) List offsets) {
        System.out.printf("%s-%d[%d] \"%s\"\n", topics.get(0), partitions.get(0), offsets.get(0), message);
    }
}

Producer example in Spring

public class Producer {
    private final KafkaTemplate kafkaTemplate;

    @Value("test-topic")
    private String topic;

    Producer(KafkaTemplate kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void send(SampleMessage message) {
        this.kafkaTemplate.send(topic, message.getMessage());
        System.out.println("Sent sample message [" + message + "] to " + topic);
    }
}

The full code example can be found here: https://github.com/CloudKarafka/springboot-kafka-example