-
-
Notifications
You must be signed in to change notification settings - Fork 27.4k
feat: Microservice Messaging Pattern (#2681) #3421
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Mukul-Howale
wants to merge
8
commits into
iluwatar:master
Choose a base branch
from
Mukul-Howale:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
118d279
Initialize microservices-messaging Spring Boot project
Mukul-Howale 9f0b50f
Initialize microservices messaging pattern
Mukul-Howale 3e422f3
Implement Message and MessageBroker classes
Mukul-Howale e72fca5
Implement messaging pattern for microservices
Mukul-Howale 5cbfd99
Expand microservices messaging docs and add diagrams
Mukul-Howale 52d6f25
Refactor to use Kafka for microservices messaging
Mukul-Howale 8d36efc
Add unit tests and license headers to messaging module
Mukul-Howale 98e442e
Refactor and simplify service and Kafka test classes
Mukul-Howale File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| --- | ||
| title: "Microservices Messaging Pattern in Java: Enabling Asynchronous Communication Between Services" | ||
| shortTitle: Microservices Messaging | ||
| description: "Learn about the Microservices Messaging pattern, a method for enabling asynchronous communication between services through message brokers to enhance decoupling, scalability, and fault tolerance in distributed systems." | ||
| category: Integration | ||
| language: en | ||
| tag: | ||
| - API design | ||
| - Asynchronous | ||
| - Cloud distributed | ||
| - Decoupling | ||
| - Enterprise patterns | ||
| - Event-driven | ||
| - Messaging | ||
| - Microservices | ||
| - Scalability | ||
| --- | ||
| ## Also known as | ||
|
|
||
| * Asynchronous Messaging | ||
| * Event-Driven Communication | ||
| * Message-Oriented Middleware (MOM) | ||
|
|
||
| ## Intent of Microservices Messaging Design Pattern | ||
|
|
||
| The Microservices Messaging pattern enables asynchronous communication between microservices through message passing, allowing for better decoupling, scalability, and fault tolerance. Services communicate by exchanging messages over messaging channels managed by a message broker. | ||
|
|
||
| ## Detailed Explanation of Microservices Messaging Pattern with Real-World Examples | ||
|
|
||
| Real-world example | ||
|
|
||
| > Imagine an e-commerce platform where a customer places an order. The Order Service publishes an "Order Created" message to a message broker. Multiple services listen to this message: the Inventory Service updates stock levels, the Payment Service processes payment, and the Notification Service sends confirmation emails. Each service operates independently, processing messages at its own pace without blocking others. If the Payment Service is temporarily down, the message broker holds the message until it recovers, ensuring no data is lost. | ||
|
|
||
| In plain words | ||
|
|
||
| > The Microservices Messaging pattern allows services to communicate asynchronously through a message broker, enabling them to work independently without waiting for each other. | ||
|
|
||
| Wikipedia says | ||
|
|
||
| > Message-oriented middleware is software or hardware infrastructure supporting sending and receiving messages between distributed systems. MOM allows application modules to be distributed over heterogeneous platforms and reduces the complexity of developing applications that span multiple operating systems and network protocols. | ||
|
|
||
| Flowchart | ||
|
|
||
|  | ||
|
|
||
|
|
||
|
|
||
| ## Programmatic Example of Microservices Messaging Pattern in Java | ||
|
|
||
|
|
||
| The Microservices Messaging pattern demonstrates how services communicate through a message broker without direct coupling. In this example, we show an order processing system where services exchange messages asynchronously. | ||
|
|
||
| The `Message` class represents the data exchanged between services. | ||
|
|
||
| ```java | ||
| public class Message { | ||
| private final String id; | ||
| private final String content; | ||
| private final LocalDateTime timestamp; | ||
|
|
||
| public Message(String content) { | ||
| this.id = UUID.randomUUID().toString(); | ||
| this.content = content; | ||
| this.timestamp = LocalDateTime.now(); | ||
| } | ||
|
|
||
| // Getters | ||
| } | ||
| ``` | ||
|
|
||
| The `MessageBroker` acts as the intermediary that routes messages between producers and consumers. | ||
|
|
||
| ```java | ||
| public class MessageBroker { | ||
| private final Map subscribers = new ConcurrentHashMap<>(); | ||
|
|
||
| public void subscribe(String topic, Consumer handler) { | ||
| subscribers.computeIfAbsent(topic, k -> new ArrayList<>()).add(handler); | ||
| } | ||
|
|
||
| public void publish(String topic, Message message) { | ||
| List<Consumer> handlers = subscribers.get(topic); | ||
| if (handlers != null) { | ||
| handlers.forEach(handler -> handler.accept(message)); | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| The `OrderService` is a message producer that publishes order messages. | ||
|
|
||
| ```java | ||
| public class OrderService { | ||
| private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class); | ||
| private final MessageBroker broker; | ||
|
|
||
| public OrderService(MessageBroker broker) { | ||
| this.broker = broker; | ||
| } | ||
|
|
||
| public void createOrder(String orderId) { | ||
| Message message = new Message("Order Created: " + orderId); | ||
| broker.publish("order-topic", message); | ||
| LOGGER.info("Published order message: {}", orderId); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| The `InventoryService` is a message consumer that processes inventory updates. | ||
|
|
||
| ```java | ||
| public class InventoryService { | ||
| private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class); | ||
|
|
||
| public void handleMessage(Message message) { | ||
| LOGGER.info("Inventory Service received: {}", message.getContent()); | ||
| LOGGER.info("Updating inventory..."); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| The `PaymentService` handles payment processing messages. | ||
|
|
||
| ```java | ||
| public class PaymentService { | ||
| private static final Logger LOGGER = LoggerFactory.getLogger(PaymentService.class); | ||
|
|
||
| public void handleMessage(Message message) { | ||
| LOGGER.info("Payment Service received: {}", message.getContent()); | ||
| LOGGER.info("Processing payment..."); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| The `main` application demonstrates the messaging pattern in action. | ||
|
|
||
| ```java | ||
| public class App { | ||
| private static final Logger LOGGER = LoggerFactory.getLogger(App.class); | ||
|
|
||
| public static void main(String[] args) throws InterruptedException { | ||
| final MessageBroker broker = new MessageBroker(); | ||
|
|
||
| final InventoryService inventoryService = new InventoryService(); | ||
| final PaymentService paymentService = new PaymentService(); | ||
|
|
||
| broker.subscribe("order-topic", inventoryService::handleMessage); | ||
| broker.subscribe("order-topic", paymentService::handleMessage); | ||
|
|
||
| final OrderService orderService = new OrderService(broker); | ||
|
|
||
| orderService.createOrder("ORDER-123"); | ||
|
|
||
| Thread.sleep(1000); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| Console output: | ||
|
|
||
| ``` | ||
| Published order message: ORDER-123 | ||
| Inventory Service received: Order Created: ORDER-123 | ||
| Updating inventory... | ||
| Payment Service received: Order Created: ORDER-123 | ||
| Processing payment... | ||
| ``` | ||
|
|
||
| Sequence Diagram | ||
|
|
||
|  | ||
|
|
||
|
|
||
|
|
||
| ## When to Use the Microservices Messaging Pattern in Java | ||
|
|
||
| * When services need to communicate without blocking each other. | ||
| * In systems requiring loose coupling between components. | ||
| * For event-driven architectures where multiple services react to events. | ||
| * When you need to handle traffic spikes by buffering messages. | ||
| * In distributed systems where services may be temporarily unavailable. | ||
|
|
||
| ## Real-World Applications of Microservices Messaging Pattern in Java | ||
|
|
||
| * Java applications using Apache Kafka, RabbitMQ, or ActiveMQ for service communication. | ||
| * E-commerce platforms for order processing and inventory management. | ||
| * Financial services for transaction processing and notifications. | ||
| * IoT systems for sensor data processing and event handling. | ||
|
|
||
| ## Benefits and Trade-offs of Microservices Messaging Pattern | ||
|
|
||
| * Services are loosely coupled and can be developed and deployed independently. | ||
| * Message buffering improves system resilience when services are temporarily unavailable. | ||
| * Supports multiple communication patterns like publish/subscribe and request/reply. | ||
| * Enhances scalability by allowing parallel message processing. | ||
| * Natural support for event-driven architectures. | ||
|
|
||
| Trade-offs: | ||
|
|
||
| * Introduces additional complexity with the message broker infrastructure. | ||
| * Requires high availability setup for the message broker. | ||
| * Eventual consistency instead of immediate consistency. | ||
| * Debugging asynchronous flows is more complex than synchronous calls. | ||
| * Need to handle message duplication and ensure idempotent consumers. | ||
|
|
||
| ## Related Java Design Patterns | ||
|
|
||
| * [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Uses messaging to coordinate distributed transactions. | ||
| * [CQRS Pattern](https://java-design-patterns.com/patterns/cqrs/): Often uses messaging to separate read and write operations. | ||
| * [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Stores state changes as messages. | ||
| * [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Complements messaging for synchronous requests. | ||
|
|
||
| ## References and Credits | ||
|
|
||
| * [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3vLKqET) | ||
| * [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) | ||
| * [Building Event-Driven Microservices: Leveraging Organizational Data at Scale](https://amzn.to/3PihS9R) | ||
| * [Pattern: Messaging (microservices.io)](https://microservices.io/patterns/communication-style/messaging.html) | ||
| * [Apache Kafka Documentation](https://kafka.apache.org/documentation/) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+186 KB
microservices-messaging/etc/microservices-messaging-sequence-diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!-- | ||
|
|
||
| This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). | ||
|
|
||
| The MIT License | ||
| Copyright © 2014-2022 Ilkka Seppälä | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
|
|
||
| --> | ||
| <project xmlns="http://maven.apache.org/POM/4.0.0" | ||
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 | ||
| http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
|
|
||
| <parent> | ||
| <groupId>com.iluwatar</groupId> | ||
| <artifactId>java-design-patterns</artifactId> | ||
| <version>1.26.0-SNAPSHOT</version> | ||
| </parent> | ||
|
|
||
| <artifactId>microservices-messaging</artifactId> | ||
| <version>1.26.0-SNAPSHOT</version> | ||
|
|
||
| <properties> | ||
| <kafka.version>3.6.1</kafka.version> | ||
| </properties> | ||
|
|
||
| <dependencies> | ||
| <!-- Kafka Client --> | ||
| <dependency> | ||
| <groupId>org.apache.kafka</groupId> | ||
| <artifactId>kafka-clients</artifactId> | ||
| <version>${kafka.version}</version> | ||
| </dependency> | ||
|
|
||
| <!-- Logging --> | ||
| <dependency> | ||
| <groupId>org.slf4j</groupId> | ||
| <artifactId>slf4j-api</artifactId> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>ch.qos.logback</groupId> | ||
| <artifactId>logback-classic</artifactId> | ||
| </dependency> | ||
|
|
||
| <!-- JSON Processing --> | ||
| <dependency> | ||
| <groupId>com.fasterxml.jackson.core</groupId> | ||
| <artifactId>jackson-databind</artifactId> | ||
| <version>2.16.1</version> | ||
| </dependency> | ||
|
|
||
| <!-- Testing --> | ||
| <dependency> | ||
| <groupId>org.junit.jupiter</groupId> | ||
| <artifactId>junit-jupiter-engine</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.mockito</groupId> | ||
| <artifactId>mockito-core</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.fasterxml.jackson.datatype</groupId> | ||
| <artifactId>jackson-datatype-jsr310</artifactId> | ||
| <version>2.19.2</version> | ||
| <scope>compile</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.junit.jupiter</groupId> | ||
| <artifactId>junit-jupiter-api</artifactId> | ||
| <version>5.12.2</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| </dependencies> | ||
|
|
||
| <build> | ||
| <plugins> | ||
| <plugin> | ||
| <groupId>org.apache.maven.plugins</groupId> | ||
| <artifactId>maven-assembly-plugin</artifactId> | ||
| <executions> | ||
| <execution> | ||
| <configuration> | ||
| <archive> | ||
| <manifest> | ||
| <mainClass>com.iluwatar.messaging.App</mainClass> | ||
| </manifest> | ||
| </archive> | ||
| </configuration> | ||
| </execution> | ||
| </executions> | ||
| </plugin> | ||
| </plugins> | ||
| </build> | ||
| </project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This class does not exist in the code