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<Integer> partitions,
                               @Header(KafkaHeaders.RECEIVED_TOPIC) List<String> topics,
                               @Header(KafkaHeaders.OFFSET) List<Long> 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<String, String> kafkaTemplate;

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

    Producer(KafkaTemplate<String, String> 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