Skip to content

Commit a563344

Browse files
authored
feat: microservice messaging pattern (#3564)
* Initialize microservices-messaging Spring Boot project Add initial project structure for microservices-messaging using Spring Boot. Includes Maven configuration with dependencies for Kafka, Lombok, and testing, as well as main application, test class, and application properties. * Initialize microservices messaging pattern 1. Added initial project structure for demonstrating the microservices messaging pattern. 2. Introduced service stubs (OrderService, InventoryService, PaymentService, NotificationService), a Message and MessageBroker class, and a main App entry point. 3. Added README and logging configuration. * Implement Message and MessageBroker classes 1. Added the Message class with unique ID, content, and timestamp fields, and a toString method. 2. Implemented the MessageBroker class to support topic-based publish-subscribe messaging, including subscriber management, message publishing, and logging. * Implement messaging pattern for microservices 1. Added message handling logic to InventoryService, PaymentService, and NotificationService. 2. OrderService now publishes order events to a MessageBroker, and App demonstrates the messaging workflow. 3. Each service processes relevant order events and logs actions for demonstration purposes. * Expand microservices messaging docs and add diagrams 1. Enhanced the README with detailed explanations, real-world examples, Java code samples, and references for the Microservices Messaging pattern. 2. Added flowchart and sequence diagram images to illustrate the pattern. * Refactor to use Kafka for microservices messaging 1. Added Apache Kafka for asynchronous communication between services. 2. Added KafkaMessageProducer and KafkaMessageConsumer classes, updated service implementations and main application logic to use Kafka, and adjusted the Maven configuration to include Kafka and Jackson dependencies. 3. Updated and moved all classes to the com.iluwatar.messaging package, improved documentation, and updated diagrams to reflect the new architecture. * Add unit tests and license headers to messaging module 1. Added comprehensive unit tests for App, InventoryService, KafkaMessageConsumer, KafkaMessageProducer, Message, NotificationService, OrderService, and PaymentService. 2. Added MIT license headers to all main source files and logback.xml. 3. Updated pom.xml to include JUnit Jupiter as a test dependency. * Refactor and simplify service and Kafka test classes 1. Simplified unit tests for InventoryService, NotificationService, and PaymentService by removing null content tests and adding instantiation checks. 2. Refactored KafkaMessageConsumerTest and KafkaMessageProducerTest to avoid requiring a real Kafka instance, focusing on class structure and method existence instead of integration behavior. * Add microservices-messaging module and run scripts Introduce the microservices-messaging module and register it in the root pom.xml. Add docker-compose.yml to run a local Kafka (confluentinc/cp-kafka) with a healthcheck, plus run-app.ps1 and run-app.sh helper scripts that start Kafka if needed and then launch the application. Update the module README with usage instructions. Also remove a duplicated junit-jupiter-api test dependency from the module pom to rely on project defaults. * microservices-messaging: code style and Lombok Add Lombok as a provided dependency and apply formatting/refactoring across the microservices-messaging module. Changes include import reordering, Javadoc and logging formatting, consistent lambda/try/catch indentation, small Kafka consumer/producer refinements (Duration/Properties usage and callback formatting), Message class tweaks (@Getter, JSON ctor and toString formatting) and EOF/newline fixes. Unit tests were also reformatted for consistency. These are non-functional style and readability improvements; no behavior changes intended. * Make Kafka producer/consumer testable Refactor KafkaMessageProducer and KafkaMessageConsumer to depend on the Producer/Consumer interfaces and add constructors that accept mockable instances. Extract default producer/consumer creation into factory methods so tests can inject MockProducer/MockConsumer. Update tests across the microservices-messaging module to use MockProducer/MockConsumer, add more meaningful assertions, error/interrupt handling tests, and simplify AppTest. These changes improve unit testability and remove the need for a running Kafka instance while preserving runtime behavior. * Format test Javadoc and reorder imports Normalize Javadoc formatting and reorder static JUnit imports for consistency in messaging tests. Converted multi-line test Javadocs to single-line comments and adjusted import ordering in the following files: - microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageConsumerTest.java - microservices-messaging/src/test/java/com/iluwatar/messaging/KafkaMessageProducerTest.java - microservices-messaging/src/test/java/com/iluwatar/messaging/OrderServiceTest.java No functional changes. * Add MIT headers and exclude .ps1 from license checks Add MIT license headers to microservices-messaging/docker-compose.yml, run-app.ps1 and run-app.sh to ensure license text is present in these scripts. Update root pom.xml to exclude PowerShell (*.ps1) files from the license plugin checks so those files are not processed by the license rule. * Add Kafka docker service to CI workflows Bring up Kafka for tests in CI and PR workflows. Adds steps to run docker compose for microservices-messaging, poll Kafka readiness (up to 20 retries), and always tear down with docker compose down. Enables Maven tests that depend on Kafka. Affects .github/workflows/maven-ci.yml and .github/workflows/maven-pr-builder.yml. * Use kafka-topics instead of kafka-topics.sh Replace calls to kafka-topics.sh with kafka-topics in CI workflows and the Docker Compose healthcheck. Updated .github/workflows/maven-ci.yml, .github/workflows/maven-pr-builder.yml, and microservices-messaging/docker-compose.yml to use the kafka-topics binary for readiness checks and healthchecks. This prevents failures on images that expose the kafka-topics command without the .sh wrapper. * Use docker compose --wait for Kafka startup Replace the custom bash readiness loop with `docker compose ... up -d --wait` in CI and PR workflows. This simplifies startup of the microservices-messaging Kafka service and removes the manual retry/polling logic. Files changed: .github/workflows/maven-ci.yml, .github/workflows/maven-pr-builder.yml. Note: requires a Docker Compose version that supports the `--wait` flag. * Reformat tests for readability Reformatted KafkaMessageConsumerTest and PaymentServiceTest for readability and consistent formatting: reflowed constructor invocation, expanded anonymous HashMap and schedulePollTask lambda blocks, and aligned assertDoesNotThrow parameters. These are pure style changes with no behavioral modifications. * Remove Kafka Docker Compose steps from CI Removed the Start/Stop Kafka Docker Service steps that ran docker compose for microservices-messaging from .github/workflows/maven-ci.yml and .github/workflows/maven-pr-builder.yml. Workflows no longer start or tear down the Kafka docker-compose service during CI/PR runs; other steps (xvfb install, Maven build, Codecov upload, Sonar cache) remain unchanged. * Bump google-java-format to 1.27.0; tidy tests Update pom.xml to use google-java-format 1.27.0 (was 1.17.0). Make minor formatting cleanups in KafkaMessageConsumerTest and PaymentServiceTest by collapsing multi-line calls into single lines. No functional changes. * Downgrade Google Java Format to 1.17.0 Update Spotless googleJavaFormat version in root pom.xml from 1.27.0 to 1.17.0 * Improve Kafka producer and consumer tests Enhance microservices-messaging tests: add consumer tests to verify run() exits immediately when stopped and gracefully handles a WakeupException (ensuring the MockConsumer is closed). Update producer error test to avoid try-with-resources, assert publish behavior and history, trigger failingProducer.errorNext(...) before closing to cover the error callback branch, then close and assert the mock producer is closed. * Refactor App.run and add messaging tests Extract App.run(...) and introduce a package-private sleepMs field to control sleep durations so the demo can be exercised programmatically and sped up for tests. Main now delegates to run; consumers are started there. Tests updated: AppTest sets sleepMs to 0 and adds testRunWithMockObjects using MockProducer/MockConsumer to exercise run without a Kafka broker; KafkaMessageProducerTest adds a null-message publish test; minor formatting fix in KafkaMessageConsumerTest. These changes improve testability and coverage for the microservices-messaging module.
1 parent 8c7a310 commit a563344

25 files changed

Lines changed: 2384 additions & 0 deletions

microservices-messaging/README.md

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
---
2+
title: "Microservices Messaging Pattern in Java: Enabling Asynchronous Communication Between Services"
3+
shortTitle: Microservices Messaging
4+
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."
5+
category: Integration
6+
language: en
7+
tag:
8+
- API design
9+
- Asynchronous
10+
- Cloud distributed
11+
- Decoupling
12+
- Enterprise patterns
13+
- Event-driven
14+
- Messaging
15+
- Microservices
16+
- Scalability
17+
---
18+
## Also known as
19+
20+
* Asynchronous Messaging
21+
* Event-Driven Communication
22+
* Message-Oriented Middleware (MOM)
23+
24+
## Intent of Microservices Messaging Design Pattern
25+
26+
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.
27+
28+
## Detailed Explanation of Microservices Messaging Pattern with Real-World Examples
29+
30+
Real-world example
31+
32+
> 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.
33+
34+
In plain words
35+
36+
> The Microservices Messaging pattern allows services to communicate asynchronously through a message broker, enabling them to work independently without waiting for each other.
37+
38+
Wikipedia says
39+
40+
> 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.
41+
42+
Flowchart
43+
44+
![Microservices Messaging flowchart](./etc/microservices-messaging-flowchart.png)
45+
46+
47+
48+
## Programmatic Example of Microservices Messaging Pattern in Java
49+
50+
51+
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.
52+
53+
The `Message` class represents the data exchanged between services.
54+
55+
```java
56+
public class Message {
57+
private final String id;
58+
private final String content;
59+
private final LocalDateTime timestamp;
60+
61+
public Message(String content) {
62+
this.id = UUID.randomUUID().toString();
63+
this.content = content;
64+
this.timestamp = LocalDateTime.now();
65+
}
66+
67+
// Getters
68+
}
69+
```
70+
71+
The `MessageBroker` acts as the intermediary that routes messages between producers and consumers.
72+
73+
```java
74+
public class MessageBroker {
75+
private final Map subscribers = new ConcurrentHashMap<>();
76+
77+
public void subscribe(String topic, Consumer handler) {
78+
subscribers.computeIfAbsent(topic, k -> new ArrayList<>()).add(handler);
79+
}
80+
81+
public void publish(String topic, Message message) {
82+
List<Consumer> handlers = subscribers.get(topic);
83+
if (handlers != null) {
84+
handlers.forEach(handler -> handler.accept(message));
85+
}
86+
}
87+
}
88+
```
89+
90+
The `OrderService` is a message producer that publishes order messages.
91+
92+
```java
93+
public class OrderService {
94+
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);
95+
private final MessageBroker broker;
96+
97+
public OrderService(MessageBroker broker) {
98+
this.broker = broker;
99+
}
100+
101+
public void createOrder(String orderId) {
102+
Message message = new Message("Order Created: " + orderId);
103+
broker.publish("order-topic", message);
104+
LOGGER.info("Published order message: {}", orderId);
105+
}
106+
}
107+
```
108+
109+
The `InventoryService` is a message consumer that processes inventory updates.
110+
111+
```java
112+
public class InventoryService {
113+
private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class);
114+
115+
public void handleMessage(Message message) {
116+
LOGGER.info("Inventory Service received: {}", message.getContent());
117+
LOGGER.info("Updating inventory...");
118+
}
119+
}
120+
```
121+
122+
The `PaymentService` handles payment processing messages.
123+
124+
```java
125+
public class PaymentService {
126+
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentService.class);
127+
128+
public void handleMessage(Message message) {
129+
LOGGER.info("Payment Service received: {}", message.getContent());
130+
LOGGER.info("Processing payment...");
131+
}
132+
}
133+
```
134+
135+
The `main` application demonstrates the messaging pattern in action.
136+
137+
```java
138+
public class App {
139+
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
140+
141+
public static void main(String[] args) throws InterruptedException {
142+
final MessageBroker broker = new MessageBroker();
143+
144+
final InventoryService inventoryService = new InventoryService();
145+
final PaymentService paymentService = new PaymentService();
146+
147+
broker.subscribe("order-topic", inventoryService::handleMessage);
148+
broker.subscribe("order-topic", paymentService::handleMessage);
149+
150+
final OrderService orderService = new OrderService(broker);
151+
152+
orderService.createOrder("ORDER-123");
153+
154+
Thread.sleep(1000);
155+
}
156+
}
157+
```
158+
159+
Console output:
160+
161+
```
162+
Published order message: ORDER-123
163+
Inventory Service received: Order Created: ORDER-123
164+
Updating inventory...
165+
Payment Service received: Order Created: ORDER-123
166+
Processing payment...
167+
```
168+
169+
Sequence Diagram
170+
171+
![Microservices Messaging sequence_diagram](./etc/microservices-messaging-sequence-diagram.png)
172+
173+
## How to Run the Application
174+
175+
### Option 1: Automated Script (Recommended)
176+
177+
Run the helper script from the module directory, which automatically starts Kafka via Docker Compose (if Docker is installed and Kafka is not already running) and launches the application:
178+
179+
* **Windows (PowerShell)**:
180+
```powershell
181+
powershell -ExecutionPolicy Bypass -File .\run-app.ps1
182+
```
183+
* **Linux / macOS**:
184+
```bash
185+
./run-app.sh
186+
```
187+
188+
### Option 2: Docker Compose
189+
190+
Start the Kafka container manually via Docker Compose and run the application:
191+
192+
```bash
193+
# Start Kafka container on port 9092
194+
docker compose up -d
195+
196+
# Run the application
197+
../mvnw compile exec:java -Dexec.mainClass="com.iluwatar.messaging.App"
198+
199+
# Stop Kafka container when finished
200+
docker compose down
201+
```
202+
203+
## When to Use the Microservices Messaging Pattern in Java
204+
205+
* When services need to communicate without blocking each other.
206+
* In systems requiring loose coupling between components.
207+
* For event-driven architectures where multiple services react to events.
208+
* When you need to handle traffic spikes by buffering messages.
209+
* In distributed systems where services may be temporarily unavailable.
210+
211+
## Real-World Applications of Microservices Messaging Pattern in Java
212+
213+
* Java applications using Apache Kafka, RabbitMQ, or ActiveMQ for service communication.
214+
* E-commerce platforms for order processing and inventory management.
215+
* Financial services for transaction processing and notifications.
216+
* IoT systems for sensor data processing and event handling.
217+
218+
## Benefits and Trade-offs of Microservices Messaging Pattern
219+
220+
* Services are loosely coupled and can be developed and deployed independently.
221+
* Message buffering improves system resilience when services are temporarily unavailable.
222+
* Supports multiple communication patterns like publish/subscribe and request/reply.
223+
* Enhances scalability by allowing parallel message processing.
224+
* Natural support for event-driven architectures.
225+
226+
Trade-offs:
227+
228+
* Introduces additional complexity with the message broker infrastructure.
229+
* Requires high availability setup for the message broker.
230+
* Eventual consistency instead of immediate consistency.
231+
* Debugging asynchronous flows is more complex than synchronous calls.
232+
* Need to handle message duplication and ensure idempotent consumers.
233+
234+
## Related Java Design Patterns
235+
236+
* [Saga Pattern](https://java-design-patterns.com/patterns/saga/): Uses messaging to coordinate distributed transactions.
237+
* [CQRS Pattern](https://java-design-patterns.com/patterns/cqrs/): Often uses messaging to separate read and write operations.
238+
* [Event Sourcing](https://java-design-patterns.com/patterns/event-sourcing/): Stores state changes as messages.
239+
* [API Gateway](https://java-design-patterns.com/patterns/microservices-api-gateway/): Complements messaging for synchronous requests.
240+
241+
## References and Credits
242+
243+
* [Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions](https://amzn.to/3vLKqET)
244+
* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O)
245+
* [Building Event-Driven Microservices: Leveraging Organizational Data at Scale](https://amzn.to/3PihS9R)
246+
* [Pattern: Messaging (microservices.io)](https://microservices.io/patterns/communication-style/messaging.html)
247+
* [Apache Kafka Documentation](https://kafka.apache.org/documentation/)
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#
2+
# This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
#
4+
# The MIT License
5+
# Copyright © 2014-2022 Ilkka Seppälä
6+
#
7+
# Permission is hereby granted, free of charge, to any person obtaining a copy
8+
# of this software and associated documentation files (the "Software"), to deal
9+
# in the Software without restriction, including without limitation the rights
10+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
# copies of the Software, and to permit persons to whom the Software is
12+
# furnished to do so, subject to the following conditions:
13+
#
14+
# The above copyright notice and this permission notice shall be included in
15+
# all copies or substantial portions of the Software.
16+
#
17+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
# THE SOFTWARE.
24+
#
25+
26+
version: '3.8'
27+
28+
services:
29+
kafka:
30+
image: confluentinc/cp-kafka:7.5.0
31+
container_name: kafka-messaging-demo
32+
ports:
33+
- "9092:9092"
34+
environment:
35+
KAFKA_NODE_ID: 1
36+
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT'
37+
KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092'
38+
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
39+
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
40+
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
41+
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
42+
KAFKA_PROCESS_ROLES: 'broker,controller'
43+
KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka:29093'
44+
KAFKA_LISTENERS: 'PLAINTEXT://kafka:29092,CONTROLLER://kafka:29093,PLAINTEXT_HOST://0.0.0.0:9092'
45+
KAFKA_INTER_BROKER_LISTENER_NAME: 'PLAINTEXT'
46+
KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
47+
KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs'
48+
CLUSTER_ID: 'MkU3OEVBNTcwNTJENDM2Qk'
49+
healthcheck:
50+
test: ["CMD-SHELL", "kafka-topics --bootstrap-server localhost:9092 --list"]
51+
interval: 5s
52+
timeout: 10s
53+
retries: 5
113 KB
Loading
186 KB
Loading

0 commit comments

Comments
 (0)