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.
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.
Record Name:UserRegistration represents a user registration event.
Fields: Define the data structure for the event.
Step 4: Generate Java Classes from Avro Schema
To work with Avro schemas in Java, you need to generate Java classes from the .avsc files.
Add Avro Maven Plugin to pom.xml:
Update the pom.xml in both user-service and notification-service to include the Avro Maven plugin for generating Java classes.
You are absolutely correct. The Avro schema definition (the .avsc file) needs to be shared between the services, not duplicated. It acts as a contract.
Q- then i create this
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
}
Implement the Producer Service:
This service handles sending messages to Kafka.
java
package com.amir.userservice.service;
import com.amir.avro.UserRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserProducerService {
private static final String TOPIC = "user-registration";
@Autowired
private KafkaTemplate<String, UserRegistration> kafkaTemplate;
public void sendUserRegistration(UserRegistration user) {
kafkaTemplate.send(TOPIC, user.getId(), user);
}
}
Configure Kafka Producer:
Ensure that application.yml is correctly set to use Avro serialization.
Run the User Service:
Start the user-service application. Ensure there are no errors and that it connects to Kafka and Schema Registry successfully.
Q- next i get this
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.
The error you're encountering in the notification-service:
code
The import com.amir.avro cannot be resolved
UserRegistration cannot be resolved to a type
indicates that the UserRegistration class isn't available in the notification-service project. This issue arises because the Avro schema and the generated Java classes are currently only present in the user-service. To enable the notification-service to consume these events, it also needs access to the UserRegistration class.
There are two primary approaches to resolve this:
Generate Avro Classes in Both Services
Create a Shared Library for Avro Schemas
Below, I'll detail both approaches so you can choose the one that best fits your project structure and future scalability needs.
Approach 1: Generate Avro Classes in Both Services
This approach involves duplicating the Avro schema in both microservices and generating the Java classes independently within each service.
Step 1: Copy the Avro Schema to Notification Service
Create the Avro Directory:
In the notification-service project, create the following directory structure:
Step 2: Configure Avro Maven Plugin in Notification Service
Update pom.xml:
Ensure that the notification-service's pom.xml includes the Avro Maven Plugin. From your previous message, it seems you already added this plugin. Here's a recap for clarity:
Navigate to the notification-service directory and execute:
Step 3: Verify the Generated Classes
Ensure that the UserRegistration.java class exists in notification-service/src/main/java/com/amir/avro/ and matches the package declaration:
java
package com.amir.avro;
// Generated code with fields: id, name, email, registrationDate
public class UserRegistration extends SpecificRecordBase {
// Fields, getters, setters, etc.
}
Step 4: Restart Notification Service
After successfully generating the Avro classes:
Refresh the Project:
If you're using an IDE like IntelliJ or Eclipse, refresh the project to recognize the newly generated classes.
Rebuild the Project:
Ensure the project builds without errors.
Run the Notification Service:
Start the notification-service application. The UserRegistration import should now resolve correctly.
Approach 2: Create a Shared Library for Avro Schemas
For better maintainability and to avoid duplicating schemas across multiple services, it's advisable to create a shared library that contains all Avro schemas and their corresponding generated classes. Both user-service and notification-service can then depend on this shared library.
Step 1: Create a Shared Avro Module
Create a New Maven Module:
Suppose you have a parent Maven project. Create a new module named avro-schemas.
Step 4: Remove Duplicate Avro Schema in Notification Service
Since the **Avro classes are now in a shared library:
Delete notification-service/src/main/resources/avro/user-registration.avsc to avoid duplication.
Ensure No Conflicting Classes:
Remove any manually added UserRegistration.java in notification-service/src/main/java/com/amir/avro/ if it exists.
Step 5: Refresh and Rebuild Both Services
For both user-service and notification-service:
Refresh the Maven Project: In your IDE, refresh Maven to recognize the new dependencies.
Rebuild the Project: Ensure there are no compilation errors.
Run Applications:
Start both user-service and notification-service. The notification-service should now recognize the UserRegistration class from the shared avro-schemas library.
Choosing the Right Approach
Approach 1 is straightforward and suitable for small projects or when services are tightly coupled.
Approach 2 is more scalable and maintainable, especially when multiple services need to share Avro schemas. It promotes DRY (Don't Repeat Yourself) principles and ensures consistency across services.
For a production-grade microservices architecture, Approach 2 is recommended.
Additional Tips
Version Control for Schemas:
Keep your Avro schemas versioned. This helps in maintaining backward compatibility when schemas evolve.
Automate Schema Distribution:
Consider using tools or scripts to automate the distribution of schemas across services, reducing manual steps and potential errors.
Use Confluent Schema Registry:
You're already using the Confluent Schema Registry, which is excellent for managing schemas centrally. Ensure that both services are correctly configured to interact with it.
Testing:
After resolving the import issue, write integration tests to ensure that messages are correctly produced and consumed between services.
Error Handling:
Implement robust error handling in consumers to handle deserialization errors or schema mismatches gracefully.
By following the steps outlined above, you should be able to resolve the UserRegistration import issue in your notification-service and ensure seamless communication between your microservices using Kafka and Avro.
If you encounter further issues or have additional questions, feel free to ask!