Practise Exercise - Microservices - Saga Pattern - Implementing the Saga Pattern in E-commerce Platform #151
Replies: 11 comments
-
1. Set Up:Dependencies:Use the Spring Initializer to generate the basic projects. Ensure you include the following dependencies for both services:
2. Application Properties:For both spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guestNote: Install RabbitMQ locally or use Docker. 3. Define the Domains:
4. Implement the Saga Workflow:For simplification, you can use the synchronous HTTP request-response model. OrderService: @RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
@Autowired
private RestTemplate restTemplate; // Ensure you've this bean created
@PostMapping
public ResponseEntity<String> placeOrder(@RequestBody Order order) {
order.setStatus("PLACED");
orderRepository.save(order);
// Communicate with the PaymentService
String paymentResult = restTemplate.postForObject("http://localhost:8081/payments", order.getId(), String.class);
if ("SUCCESS".equals(paymentResult)) {
order.setStatus("PAID");
orderRepository.save(order);
return ResponseEntity.ok("Order placed and payment processed successfully!");
} else {
order.setStatus("FAILED");
orderRepository.save(order);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Payment processing failed.");
}
}
}PaymentService: @RestController
@RequestMapping("/payments")
public class PaymentController {
@Autowired
private PaymentRepository paymentRepository;
@PostMapping
public ResponseEntity<String> processPayment(@RequestBody Long orderId) {
Payment payment = new Payment();
payment.setOrderId(orderId);
// Dummy logic to simulate payment processing
if (new Random().nextBoolean()) { // Randomly succeeds or fails
payment.setStatus("COMPLETED");
paymentRepository.save(payment);
return ResponseEntity.ok("SUCCESS");
} else {
payment.setStatus("FAILED");
paymentRepository.save(payment);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("FAILED");
}
}
}5. Handle Compensating Transactions:This is primarily handled in the 6. Testing:To test, run both services. Use Postman or any API testing tool to place an order via the OrderService and see if the PaymentService processes the payment. Note that the payment might randomly fail or succeed due to the dummy logic. Hints/Tips:
This exercise provides a practical, hands-on understanding of the Saga pattern with Spring Boot, even for beginners. After grasping this, learners can explore more advanced saga implementations using event-driven architectures. |
Beta Was this translation helpful? Give feedback.
-
|
Hi @akash-coded Name: Jay Prakash Kumar Implemented SAGA Pattren using event-driven messaging architecture with RabbitMQ in order and payment service. Payment status will be updated whenever a new order gets placed. If payment is not found order status will updated to failed. Here are the repositories - |
Beta Was this translation helpful? Give feedback.
-
|
Hi Thanks |
Beta Was this translation helpful? Give feedback.
-
|
Hi @akash-coded Please find below the implementation for Saga pattern |
Beta Was this translation helpful? Give feedback.
-
|
Hi @akash-coded |
Beta Was this translation helpful? Give feedback.
-
|
Hi Akash ( @akash-coded ), Please find the code base attached for saga pattern - Coreography approach Saga orchestration pattern:
CQRS Pattern:
Placeholder code for capstone. To avoid losing of code done, storing it in temporary location once completed to be updated in 149 / lms capstone_hotel_reservation_system.zip Name: Arul |
Beta Was this translation helpful? Give feedback.
-
|
Hi Akash, Here are the two repos, Order service URL as below: Regards |
Beta Was this translation helpful? Give feedback.
-
|
Hi Akash, Please find the choreography codebase below for 151: The Orchestrator code base is: Thanks, |
Beta Was this translation helpful? Give feedback.
-
|
Hi Akash, saga_pattern_choreography_1.zip Thanks, |
Beta Was this translation helpful? Give feedback.
-
|
Hi @akash-coded , Sharing my code in zip file for Practise Exercise - Microservices - Saga Pattern - Implementing the Saga Pattern in E-commerce Platform Name: Harsh Pandya |
Beta Was this translation helpful? Give feedback.
-
|
Hi Akash, SAGA.zip |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Let's create a simple yet meaningful exercise to help learners understand the Saga pattern using a simplified e-commerce platform consisting of an Order Service and a Payment Service.
Scenario:
Imagine a user wants to buy a product. They place an order, and the system should then check if there's stock, reserve the stock, make a payment, and then finalize the order. If any step fails, appropriate compensating actions should be taken.
Exercise: Implementing the Saga Pattern in E-commerce Platform
1. Set Up:
OrderServiceandPaymentService.2. Define the Domains:
OrderService:
Orderentity with attributes:id,productId,userId,status(PLACED, PAID, FAILED).OrderRepositoryto interact with the database.PaymentService:
Paymententity with attributes:id,orderId,status(PENDING, COMPLETED, FAILED).PaymentRepositoryto handle database interactions.3. Implement the Saga Workflow:
OrderService.OrderServicechecks stock and reserves the product.OrderServicesends a message (event) toPaymentServiceto initiate payment.PaymentServicetries to process the payment.PaymentServicesends a success message back toOrderService.PaymentServicesends a failure message toOrderService.4. Implementing the Messaging:
OrderServiceshould listen for payment success and failure events.PaymentServiceshould listen for order placement events.5. Handle Compensating Transactions:
PaymentServicereceives a failure event:PaymentServiceprocesses payment successfully:OrderService.6. Testing:
OrderServicework correctly.Tips:
@StreamListenerin Spring Cloud Stream to handle incoming messages.Further Enhancements:
StockServiceto manage product stock. Extend the saga to communicate with this service too.This exercise gives a basic yet comprehensive understanding of the Saga pattern.
Hints/Tips:
1. Set Up:
Dependencies:
Use the Spring Initializer to generate the basic projects. Ensure you include the following dependencies for both services:
2. Application Properties:
For both
OrderServiceandPaymentService, insrc/main/resources/application.properties:Note: Install RabbitMQ locally or use Docker.
3. Define the Domains:
OrderService:
Order Entity
OrderRepository
PaymentService:
Payment Entity
PaymentRepository
4. Implement the Saga Workflow:
For simplification, you can use the synchronous HTTP request-response model.
5. Other Points to Note:
To set up
RestTemplatebean, add the following to your main@SpringBootApplicationclass:It might be beneficial to use service discovery like Eureka in a more complex scenario, so services can discover each other rather than hardcoding URLs.
The above steps demonstrate a simple, synchronous saga. In a real-world scenario, using events and asynchronous communication is more resilient and scalable.
Make sure RabbitMQ is running. If you're using Docker, the command might be:
docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management.Use the H2 console to verify data at
http://localhost:<port>/h2-console.Beta Was this translation helpful? Give feedback.
All reactions