Certainly! Let's create a step-by-step tutorial to build a Reactive Kafka Consumer and Producer using Spring Boot. This guide will help you set up a project similar to the example-reactive-spring-kafka-consumer-and-producer repository.
Bootstrap Servers: Ensure this matches your Kafka broker's address and port.
Serialization:
Producers serialize keys and values using StringSerializer and JsonSerializer respectively.
Consumers deserialize keys and values using StringDeserializer and JsonDeserializer respectively, with options to trust all packages for JSON deserialization.
Implement Reactive Services
We'll create two services: one for producing messages to Kafka and another for consuming messages from Kafka.
Upon sending, you should see logs indicating the message was sent and subsequently consumed.
Conclusion
You've successfully set up a Reactive Kafka Consumer and Producer using Spring Boot. This setup leverages Project Reactor for non-blocking, asynchronous processing, making your application highly scalable and efficient.
Next Steps
Error Handling: Enhance resilience by implementing comprehensive error handling and retry mechanisms.
Backpressure Management: Fine-tune backpressure strategies to handle varying loads.
Security: Secure your Kafka brokers and implement authentication and authorization as needed.
Monitoring: Integrate monitoring tools like Prometheus and Grafana to observe Kafka metrics.
Feel free to explore and extend this setup according to your application's requirements. Happy coding!
Q- just i want you instead of local kafak server and zookeper just use docker compose oki
Q- just reriwe the full tutor just make it using docker compose intead of local bin files
Certainly! Let's update the Reactive Kafka Consumer and Producer tutorial to use Docker Compose for setting up Kafka and ZooKeeper instead of installing them locally. This approach simplifies the setup process and ensures a consistent environment across different machines.
Table of Contents
Prerequisites
Project Setup
Add Necessary Dependencies
Define Data Transfer Objects (DTOs)
Configure Kafka Consumer and Producer
Implement Reactive Services
Testing the Application
Running the Application
Conclusion
Prerequisites
Before you begin, ensure you have the following installed on your machine:
Java Development Kit (JDK) 8 or higher
Maven for project management and build
Docker and Docker Compose for containerizing Kafka and ZooKeeper
An IDE like IntelliJ IDEA or Eclipse (optional but recommended)
service/: Services for producing and consuming messages.
ReactiveKafkaConsumerProducerApplication.java: Main application class.
application.properties: Configuration properties.
Add Necessary Dependencies
Update your pom.xml to include the required dependencies for Spring Boot, Kafka, and Reactor.
xml
Notes:
Reactor Kafka Version: Ensure that the reactor.kafka.version is compatible with your Spring Boot version. Adjust it to the latest stable version if necessary.
Lombok: If you prefer using Lombok to reduce boilerplate code, include it as shown. Otherwise, you can omit Lombok dependencies and manually write getters, setters, etc.
Define Data Transfer Objects (DTOs)
Create DTOs representing the data you intend to send and consume via Kafka.
Bootstrap Servers: Ensure this matches your Kafka broker's address and port (localhost:9092 as per Docker Compose).
Serialization:
Producers serialize keys and values using StringSerializer and JsonSerializer respectively.
Consumers deserialize keys and values using StringDeserializer and JsonDeserializer respectively, with options to trust all packages for JSON deserialization.
Implement Reactive Services
We'll create two services: one for producing messages to Kafka and another for consuming messages from Kafka.
1. ReactiveProducerService.java
java
package com.example.reactivekafkaconsumerandproducer.service;
import com.example.reactivekafkaconsumerandproducer.dto.FakeProducerDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.reactive.ReactiveKafkaProducerTemplate;
import org.springframework.stereotype.Service;
@Service
public class ReactiveProducerService {
private static final Logger log = LoggerFactory.getLogger(ReactiveProducerService.class);
private final ReactiveKafkaProducerTemplate<String, FakeProducerDTO> reactiveKafkaProducerTemplate;
@Value("${FAKE_PRODUCER_DTO_TOPIC}")
private String topic;
public ReactiveProducerService(ReactiveKafkaProducerTemplate<String, FakeProducerDTO> reactiveKafkaProducerTemplate) {
this.reactiveKafkaProducerTemplate = reactiveKafkaProducerTemplate;
}
public void send(FakeProducerDTO fakeProducerDTO) {
log.info("Sending to topic={}, DTO={}", topic, fakeProducerDTO);
reactiveKafkaProducerTemplate.send(topic, fakeProducerDTO)
.doOnSuccess(senderResult -> log.info("Sent DTO={} to offset={}", fakeProducerDTO, senderResult.recordMetadata().offset()))
.doOnError(e -> log.error("Error sending DTO={} due to {}", fakeProducerDTO, e.getMessage()))
.subscribe();
}
}
Explanation:
send Method:
Logs the DTO being sent.
Sends the DTO to the specified Kafka topic.
Logs the successful send with the record offset or logs an error if the send fails.
Logs received records with key, value, topic, and offset.
Maps the ConsumerRecord to the value (FakeConsumerDTO).
Logs successful consumption or errors.
CommandLineRunner Implementation:
Automatically starts consuming messages when the application starts.
3. KafkaController.java (Optional)
To facilitate sending messages via HTTP requests, we'll create a REST controller.
java
package com.example.reactivekafkaconsumerandproducer.controller;
import com.example.reactivekafkaconsumerandproducer.dto.FakeProducerDTO;
import com.example.reactivekafkaconsumerandproducer.service.ReactiveProducerService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class KafkaController {
private final ReactiveProducerService reactiveProducerService;
public KafkaController(ReactiveProducerService reactiveProducerService) {
this.reactiveProducerService = reactiveProducerService;
}
@PostMapping("/send")
public ResponseEntity<String> sendMessage(@RequestBody FakeProducerDTO dto) {
reactiveProducerService.send(dto);
return ResponseEntity.ok("Message sent to Kafka topic");
}
}
Explanation:
/api/send Endpoint:
Accepts POST requests with a JSON body representing FakeProducerDTO.
Invokes the ReactiveProducerService to send the message to Kafka.
Returns a success response.
Testing the Application
Creating integration tests ensures that your Kafka consumer and producer are functioning as expected.
1. ReactiveProducerServiceIntegrationTest.java
java
package com.example.reactivekafkaconsumerandproducer;
import com.example.reactivekafkaconsumerandproducer.dto.FakeProducerDTO;
import com.example.reactivekafkaconsumerandproducer.service.ReactiveProducerService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
// Optionally, you can use embedded Kafka for testing purposes
@SpringBootTest
public class ReactiveProducerServiceIntegrationTest {
@Autowired
private ReactiveProducerService reactiveProducerService;
@Test
public void testSend() {
FakeProducerDTO dto = new FakeProducerDTO("1", "Test Message");
reactiveProducerService.send(dto);
// Add assertions or verify via logs
}
}
2. ReactiveConsumerServiceIntegrationTest.java
java
package com.example.reactivekafkaconsumerandproducer;
import com.example.reactivekafkaconsumerandproducer.dto.FakeConsumerDTO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import org.springframework.kafka.core.reactive.ReactiveKafkaConsumerTemplate;
// Optionally, you can use embedded Kafka for testing purposes
@SpringBootTest
public class ReactiveConsumerServiceIntegrationTest {
@Autowired
private ReactiveKafkaConsumerTemplate<String, FakeConsumerDTO> reactiveKafkaConsumerTemplate;
@Test
public void testConsume() {
Flux<FakeConsumerDTO> consumerFlux = reactiveKafkaConsumerTemplate.receiveAutoAck()
.map(record -> record.value());
StepVerifier.create(consumerFlux)
.expectNextMatches(dto -> dto.getId().equals("1") && dto.getContent().equals("Test Content"))
.thenCancel()
.verify();
}
}
Note: For robust testing, consider using Embedded Kafka to run Kafka within your tests. This allows you to perform integration tests without relying on external Kafka brokers.
Running the Application
Follow these steps to run your Spring Boot application alongside Kafka and ZooKeeper using Docker Compose.
1. Ensure Kafka and ZooKeeper Are Running
If you haven't already started Kafka and ZooKeeper using Docker Compose, navigate to the kafka directory and run:
bash
docker-compose up -d
2. Build the Project
Navigate to your project's root directory and run:
bash
mvn clean install
Explanation:
This command cleans any previous builds and installs the project along with its dependencies.
3. Run the Spring Boot Application
Start the application using Maven:
bash
mvn spring-boot:run
Alternative: You can also run the application from your IDE by running the ReactiveKafkaConsumerProducerApplication class.
Upon Startup:
The ReactiveConsumerService will begin consuming messages from the fake_consumer_dto_topic.
The consumer will automatically subscribe to the topic and start listening for incoming messages.
4. Produce Messages
You can produce messages to Kafka in multiple ways. Below are two approaches:
4.1. Using the REST Controller (Recommended)
If you've implemented the KafkaController, you can send messages via HTTP requests.
The producer sends the FakeProducerDTO to the fake_producer_dto_topic.
If you have another service/listener consuming from this topic, it will receive the message accordingly.
The ReactiveConsumerService will log the consumption of messages from the fake_consumer_dto_topic.
4.2. Manually Triggering the Producer (Without REST Controller)
If you prefer not to use HTTP endpoints, you can modify the ReactiveKafkaConsumerProducerApplication to send messages upon startup or via scheduled tasks.
Example:
java
package com.example.reactivekafkaconsumerandproducer;
import com.example.reactivekafkaconsumerandproducer.dto.FakeProducerDTO;
import com.example.reactivekafkaconsumerandproducer.service.ReactiveProducerService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class ReactiveKafkaConsumerProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ReactiveKafkaConsumerProducerApplication.class, args);
}
@Bean
CommandLineRunner sendMessages(ReactiveProducerService producerService) {
return args -> {
FakeProducerDTO dto = new FakeProducerDTO("123", "Hello from CommandLineRunner!");
producerService.send(dto);
};
}
}
Explanation:
This configuration sends a message to Kafka as soon as the application starts.
Conclusion
You've successfully set up a Reactive Kafka Consumer and Producer using Spring Boot with Docker Compose managing your Kafka and ZooKeeper services. This setup leverages Project Reactor for non-blocking, asynchronous processing, making your application highly scalable and efficient.
Next Steps
Error Handling: Enhance resilience by implementing comprehensive error handling and retry mechanisms.
Backpressure Management: Fine-tune backpressure strategies to handle varying loads.
Security: Secure your Kafka brokers and implement authentication and authorization as needed.
Monitoring: Integrate monitoring tools like Prometheus and Grafana to observe Kafka metrics.
Scaling: Explore scaling Kafka consumers and producers based on your application's demands.
Advanced Configurations: Dive deeper into Kafka configurations to optimize performance and reliability.