Write a Kafka producer with Java using Spring Boot
Sometime ago I set up my Raspberry board with a temperature and humidity sensor and configured it to publish data to a Kafka cluster (you can read the 2-article series starting from the first article here https://medium.com/@robertopozzi/using-sensors-with-raspberry-boards-part-1-sending-data-to-kafka-8b7a545949f9).
The component to read sensor data and send it to a Kafka topic was a Kafka producer written in Python; since Kafka, by nature, is agnostic about the technology you use to interact with it, in this article I want to use Java instead, and I chose to use Spring Boot (https://docs.spring.io/spring-boot/docs/3.1.0-SNAPSHOT/reference/html/index.html).
To experiment with Java based Kafka client I setup a very simple scenario, in which I simulate the behavior of a real sensor that continuously reads data from the surrounding environment and sends to an external sink:
- The class SensorSimulator simulates the real sensor, producing temperature and humidity data as random integers within a pre-determined range;
- The class TemperatureSensorSimulationService works as a Kafka Producer, implementing the logic to publish temperature and humidity data to a Kafka topic named temperatures.