Create a microservices-based application using Spring Boot, where two separate microservices communicate asynchronously through Kafka. This project will help you understand the fundamentals of microservices architecture, Spring Boot integration with Kafka, and inter-service communication patterns.
Components:
Microservice A: Acts as a producer that sends messages/events to a Kafka topic. For example, a "User Service" that publishes user registration events.
Microservice B: Acts as a consumer that listens to the Kafka topic and processes the incoming messages. For example, a "Notification Service" that sends welcome emails when a new user registers.
Kafka Broker: Facilitates the message exchange between the two microservices.
Spring Boot: Framework used to build both microservices with easy integration to Kafka using Spring Kafka.
Key Learning Points:
Setting up Spring Boot applications with Kafka dependencies.
Configuring Kafka producers and consumers in Spring Boot.
Understanding topics, partitions, and consumer groups.
Great! You've successfully set up your Docker environment with Kafka, Zookeeper, and Schema Registry, and you've initialized both the user-service and notification-service applications with their respective pom.xml and application.yml configurations.
Now, let's proceed with the next steps to implement the User Service as a Kafka Producer and the Notification Service as a Kafka Consumer. Here's a detailed roadmap:
Step 3: Define the Avro Schema
Before sending messages between microservices, it's essential to define a schema that both services will agree upon. We'll use Avro for schema definition.
Create a Directory for Schemas:
In your project root (you can choose either user-service or notification-service), create a directory to store your Avro schemas.
Run the following Maven command in both user-service and notification-service to generate the Avro Java classes:
bash
mvn clean compile
This will generate the UserRegistration.java class in src/main/java/com/amir/avro/.
Step 5: Implement the User Service (Producer)
The User Service will expose a REST API to create a new user, which will then publish a UserRegistration event to Kafka.
Create the UserRegistration Model:
The Avro plugin should have generated a class similar to this:
java
package com.amir.avro;
import org.apache.avro.specific.SpecificRecordBase;
import org.apache.avro.Schema;
public class UserRegistration extends SpecificRecordBase {
private String id;
private String name;
private String email;
private long registrationDate;
// Getters and Setters
// ...
}
Create a REST Controller:
Create a REST controller to handle user registration.
java
package com.amir.userservice.controller;
import com.amir.avro.UserRegistration;
import com.amir.userservice.service.UserProducerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.UUID;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserProducerService userProducerService;
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody UserDTO userDTO) {
UserRegistration user = new UserRegistration();
user.setId(UUID.randomUUID().toString());
user.setName(userDTO.getName());
user.setEmail(userDTO.getEmail());
user.setRegistrationDate(Instant.now().toEpochMilli());
userProducerService.sendUserRegistration(user);
return ResponseEntity.ok("User registered successfully");
}
}
// DTO Class
class UserDTO {
private String name;
private String email;
// Getters and Setters
}
Step 6: Implement the Notification Service (Consumer)
The Notification Service will listen to the user-registration topic and process incoming UserRegistration events by sending a welcome email (simulated).
Create a Consumer Configuration:
Define how the Notification Service will consume messages from Kafka.
Now that both services are up and running, let's test the entire flow.
Ensure Kafka Topic Exists:
If the topic user-registration doesn’t exist, Kafka will create it automatically when a message is sent. However, you can also manually create the topic using Kafka's CLI:
Should show that it sent a UserRegistration event to Kafka.
Notification Service Logs:
Should show that it received the UserRegistration event.
Should simulate sending a welcome email.
Sample Logs:
User Service:
code
2023-04-28 12:00:00 INFO [UserProducerService] Sent message: UserRegistration{id='1234', name='John Doe', email='john.doe@example.com', registrationDate=1682678400000}
Notification Service:
code
2023-04-28 12:00:05 INFO [UserRegistrationListener] Received User Registration event: UserRegistration{id='1234', name='John Doe', email='john.doe@example.com', registrationDate=1682678400000}
2023-04-28 12:00:05 INFO [UserRegistrationListener] Sending welcome email to john.doe@example.com
Start the notification-service application. Ensure it connects to Kafka and Schema Registry without issues and starts listening to the user-registration topic.
Explanation:
FixedBackOff: Specifies the time interval between retries and the maximum number of retry attempts.
SeekToCurrentErrorHandler: Handles the error by seeking the offset of the failed message, allowing retries.
Handle Exceptions in Listener:
Modify the listener to handle potential exceptions.
java
package com.amir.notificationservice.listener;
import com.amir.avro.UserRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class UserRegistrationListener {
private static final Logger logger = LoggerFactory.getLogger(UserRegistrationListener.class);
@KafkaListener(topics = "user-registration", groupId = "notification-service-group", containerFactory = "kafkaListenerContainerFactory")
public void handleUserRegistration(UserRegistration user) {
try {
logger.info("Received User Registration event: {}", user);
// Simulate sending a welcome email
sendWelcomeEmail(user);
} catch (Exception e) {
logger.error("Error processing user registration: {}", e.getMessage());
throw e; // Throw exception to trigger retry
}
}
private void sendWelcomeEmail(UserRegistration user) {
// Simulate a potential failure
if (user.getEmail() == null) {
throw new RuntimeException("Email is null");
}
logger.info("Sending welcome email to {}", user.getEmail());
}
}
Explanation:
If email is null, it throws a RuntimeException, which triggers the retry mechanism.
Proper logging helps in monitoring and debugging.
Test Error Handling:
Scenario 1: Successful Event
Send a valid user registration event and observe normal processing.
Scenario 2: Invalid Event
Modify the UserController to allow sending a user with a null email:
java
// In UserController
@PostMapping("/register-invalid")
public ResponseEntity<String> registerInvalidUser(@RequestBody UserDTO userDTO) {
UserRegistration user = new UserRegistration();
user.setId(UUID.randomUUID().toString());
user.setName(userDTO.getName());
user.setEmail(null); // Intentionally set to null
user.setRegistrationDate(Instant.now().toEpochMilli());
userProducerService.sendUserRegistration(user);
return ResponseEntity.ok("Invalid user registration sent");
}
Send a POST request to /users/register-invalid and observe that the notification-service retries the processing three times before failing.
After updating the docker-compose.yml, rebuild the images and start all services.
bash
docker-compose up --build -d
Verify Services are Running:
Use docker ps to ensure all containers are up and running. Access the APIs via their exposed ports (8082 for user-service and 8083 for notification-service).