事件驱动的微服务集成
学习使用 Kafka 设计并实现微服务之间的异步通信模式。
事件驱动的微服务集成 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Event-Driven Microservices
Welcome to Event-Driven Microservice Integration! In this lesson, we'll learn how microservices can communicate asynchronously using events.
An event-driven architecture (EDA) is a software design pattern where services communicate by producing and consuming "events." These events are records of something that happened.
This approach helps create highly decoupled, scalable, and resilient systems.
Benefits of Asynchronous
Why choose event-driven communication over direct API calls (synchronous)?
- Decoupling: Services don't need to know about each other's existence. They only care about events.
- Resilience: If a consuming service is down, the events are stored and processed later, preventing cascading failures.
- Scalability: Producers can publish events without waiting for consumers, and multiple consumers can process events in parallel.
Kafka as Event Bus
Apache Kafka acts as a central "event bus" or message broker in many event-driven architectures.
Producers send events to Kafka topics, and consumers read events from these topics. Kafka stores these events durably, ensuring no data loss.
This allows services to communicate without direct connections, simplifying their design and deployment.
An OrderCreated Event
An event is a lightweight message indicating that something significant has occurred. It typically includes the event type, a timestamp, and relevant data.
Let's define a simple OrderCreatedEvent that our OrderService might publish when a new order is placed.
public class OrderCreatedEvent {
private String orderId;
private String customerId;
private double amount;
private long timestamp;
public OrderCreatedEvent(String orderId, String customerId, double amount) {
this.orderId = orderId;
this.customerId = customerId;
this.amount = amount;
this.timestamp = System.currentTimeMillis();
}
public String getOrderId() { return orderId; }
public String getCustomerId() { return customerId; }
public double getAmount() { return amount; }
public long getTimestamp() { return timestamp; }
@Override
public String toString() {
return "OrderCreatedEvent{" +
"orderId='" + orderId + '\'' +
", customerId='" + customerId + '\'' +
", amount=" + amount +
", timestamp=" + timestamp +
'}';
}
}Order Service as Producer
Our OrderService is responsible for creating new orders. Once an order is successfully created, it publishes an OrderCreatedEvent to a Kafka topic.
This event can then be consumed by other services, like an InventoryService, without the OrderService needing to know anything about them.
// Simulates a Kafka producer component
public class OrderProducer {
public void sendOrderCreatedEvent(OrderCreatedEvent event) {
// In a real Spring Boot app, this would use KafkaTemplate.send()
System.out.println("Producer: Sending event to Kafka topic 'orders':");
System.out.println(" " + event.toString());
}
}Try the Producer
Here's how you'd typically trigger the producer logic. Run this code to see the simulated event being "sent."
// Represents an event when an order is created
class OrderCreatedEvent {
private String orderId;
private String customerId;
private double amount;
private long timestamp;
public OrderCreatedEvent(String orderId, String customerId, double amount) {
this.orderId = orderId;
this.customerId = customerId;
this.amount = amount;
this.timestamp = System.currentTimeMillis();
}
public String getOrderId() { return orderId; }
public String getCustomerId() { return customerId; }
public double getAmount() { return amount; }
public long getTimestamp() { return timestamp; }
@Override
public String toString() {
return "OrderCreatedEvent{" +
"orderId='" + orderId + '\'' +
", customerId='" + customerId + '\'' +
", amount=" + amount +
", timestamp=" + timestamp +
'}';
}
}
// Simulates a Kafka producer component
class OrderProducer {
public void sendOrderCreatedEvent(OrderCreatedEvent event) {
System.out.println("Producer: Sending event to Kafka topic 'orders':");
System.out.println(" " + event.toString());
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Order Service simulation started.");
OrderProducer producer = new OrderProducer();
// Simulate an order creation
OrderCreatedEvent event = new OrderCreatedEvent("ORD-001", "CUST-123", 99.99);
producer.sendOrderCreatedEvent(event);
System.out.println("Order Service simulation finished.");
}
}Inventory Service as Consumer
Our InventoryService needs to know when new orders are placed so it can update stock levels. It listens for OrderCreatedEvents from the Kafka topic.
When an event arrives, the consumer processes it, perhaps by deducting items from inventory or initiating a fulfillment process.
// Simulates a Kafka consumer component
public class InventoryConsumer {
public void listenOrderCreatedEvent(OrderCreatedEvent event) {
// In a real Spring Boot app, this would be an @KafkaListener method
System.out.println("Consumer: Received event from Kafka topic 'orders':");
System.out.println(" " + event.toString());
System.out.println(" Updating inventory for order " + event.getOrderId());
}
}Try the Consumer
This code simulates the InventoryConsumer listening for an event. In a real scenario, this would run continuously, processing incoming events.
// Represents an event when an order is created
class OrderCreatedEvent {
private String orderId;
private String customerId;
private double amount;
private long timestamp;
public OrderCreatedEvent(String orderId, String customerId, double amount) {
this.orderId = orderId;
this.customerId = customerId;
this.amount = amount;
this.timestamp = System.currentTimeMillis();
}
public String getOrderId() { return orderId; }
public String getCustomerId() { return customerId; }
public double getAmount() { return amount; }
public long getTimestamp() { return timestamp; }
@Override
public String toString() {
return "OrderCreatedEvent{" +
"orderId='" + orderId + '\'' +
", customerId='" + customerId + '\'' +
", amount=" + amount +
", timestamp=" + timestamp +
'}';
}
}
// Simulates a Kafka consumer component
class InventoryConsumer {
public void listenOrderCreatedEvent(OrderCreatedEvent event) {
System.out.println("Consumer: Received event from Kafka topic 'orders':");
System.out.println(" " + event.toString());
System.out.println(" Updating inventory for order " + event.getOrderId());
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Inventory Service simulation started.");
InventoryConsumer consumer = new InventoryConsumer();
// Simulate receiving an event (e.g., from Kafka)
// This event would typically come from a Producer
OrderCreatedEvent receivedEvent = new OrderCreatedEvent("ORD-001", "CUST-123", 99.99);
consumer.listenOrderCreatedEvent(receivedEvent);
System.out.println("Inventory Service simulation finished.");
}
}Key Considerations
When working with event-driven systems, two key concepts are important:
- Eventual Consistency: Data across different services might not be instantly consistent. It will become consistent "eventually."
- Idempotency: Consumers should be designed to handle duplicate events gracefully. Processing the same event multiple times should not change the outcome.
These are crucial for building robust asynchronous microservices.
Integration Check
Which of the following are key benefits of using an event-driven architecture for microservice integration compared to direct synchronous API calls?
Event-Driven Recap
Great job! In this lesson, you've learned about event-driven microservice integration:
- The benefits of asynchronous communication like decoupling, resilience, and scalability.
- How Kafka serves as an event bus.
- The roles of producer and consumer microservices in publishing and processing events.
- Important concepts like eventual consistency and idempotency.
You're now ready to design more robust and scalable microservice interactions!
用 AI 导师学习 Java — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 24
- 课程
- 93
常见问题解答
「事件驱动的微服务集成」课时是免费的吗?
是的 — 「事件驱动的微服务集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 3 节课。
「事件驱动的微服务集成」这节课中我会学到什么?
学习使用 Kafka 设计并实现微服务之间的异步通信模式。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「事件驱动的微服务集成」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?
能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Kafka 生产者入门
- 构建 Kafka 消费者
- 事件驱动的微服务集成