0Pricing
Microservices Communication Patterns (Saga, Circuit Breaker) · Урок

Проектирование Саг на основе событий

Спроектируйте поток хореографической Саги, используя события для запуска действий в разных микросервисах.

«Проектирование Саг на основе событий» — бесплатный урок Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Microservices Communication Patterns (Saga, Circuit Breaker), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Microservices Communication Patterns (Saga, Circuit Breaker) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Event-Driven Saga Design

Welcome! In this lesson, we'll learn how to design the flow of a Choreography Saga. This pattern helps manage complex business transactions that span multiple services.

We'll focus on using events as the primary way services communicate and trigger each other's actions.

Choreography Refresher

Remember Choreography Sagas? In this style, services communicate directly by publishing and subscribing to events.

  • No central orchestrator: Services react to events from others.
  • Decentralized decisions: Each service decides its next step based on the event it receives.

Our Business Scenario

Let's design a saga for an "Online Order Placement" system. This common scenario involves several steps across different microservices:

  • Customer places order.
  • Inventory is checked and reserved.
  • Payment is processed.
  • Order is shipped.

Identifying Core Saga Steps

For our "Order Placement" saga, we can break it down into these main steps, each potentially handled by a different service:

  • Order Service: Creates the order.
  • Inventory Service: Reserves items.
  • Payment Service: Processes payment.
  • Shipping Service: Schedules shipment.

Events Drive the Flow

In a choreography saga, each step is initiated by an event. When one service completes its task, it publishes an event.

Other services, interested in that event, subscribe to it and react accordingly. This creates a chain reaction.

Kicking Off the Saga

Every saga needs a starting point. For our "Order Placement," the Order Service initiates the process.

When a customer places an order, the Order Service creates it and publishes an OrderCreatedEvent.

Inventory Reacts to Order

The Inventory Service subscribes to OrderCreatedEvent. Upon receiving it, it attempts to reserve the items for the order.

After processing, it publishes either an InventoryReservedEvent or an InventoryFailedEvent.

class OrderCreatedEvent {
    String orderId;
    String customerId;
    // ... item details
}

class InventoryService {
    public void handleOrderCreated(OrderCreatedEvent event) {
        System.out.println("Inventory Service: Received OrderCreatedEvent for " + event.orderId);
        // Logic to reserve items...
        boolean success = true; // Assume success for now
        if (success) {
            System.out.println("Inventory Service: Items reserved. Publishing InventoryReservedEvent.");
            // In a real system, publish InventoryReservedEvent
        } else {
            System.out.println("Inventory Service: Inventory failed. Publishing InventoryFailedEvent.");
            // In a real system, publish InventoryFailedEvent
        }
    }
}

public class Main {
    public static void main(String[] args) {
        InventoryService inventory = new InventoryService();
        OrderCreatedEvent newOrder = new OrderCreatedEvent();
        newOrder.orderId = "ORD123";
        newOrder.customerId = "CUST456";

        inventory.handleOrderCreated(newOrder);
    }
}

Payment Reacts to Inventory

The Payment Service subscribes to InventoryReservedEvent. This means payment only proceeds if inventory is successfully reserved.

It processes the payment and then publishes either a PaymentProcessedEvent or a PaymentFailedEvent.

Shipping Reacts to Payment

Finally, the Shipping Service subscribes to PaymentProcessedEvent. It schedules the shipment only after payment is confirmed.

It then publishes an OrderShippedEvent to complete the main saga flow.

Planning for Rollbacks

What if a step fails? For example, if payment fails after inventory is reserved? In a choreography saga, we use compensation events.

The Payment Service would publish a PaymentFailedEvent. The Inventory Service would subscribe to this event and publish an InventoryReleasedEvent to undo its previous action.

Saga Flow Check

Consider our Order Placement saga. What is the correct sequence of events if the entire process is successful?

Recap: Designing Event Flows

We've learned how to design a choreography saga by breaking down a business transaction into steps.

  • Each step publishes an event to trigger the next.
  • We identified the initial event and subsequent events for a successful flow.
  • We also briefly considered how compensation events are used to handle failures.

Next, we'll explore how message brokers facilitate this communication!

Часто задаваемые вопросы

Урок «Проектирование Саг на основе событий» бесплатный?

Да — полный текст урока «Проектирование Саг на основе событий» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Microservices Communication Patterns (Saga, Circuit Breaker), подпишись на CoddyKit PRO. Курс Microservices Communication Patterns (Saga, Circuit Breaker) содержит 4 уроков всего.

Чему я научусь в уроке «Проектирование Саг на основе событий»?

Спроектируйте поток хореографической Саги, используя события для запуска действий в разных микросервисах. Ты практикуешь Microservices Communication Patterns (Saga, Circuit Breaker) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Microservices Communication Patterns (Saga, Circuit Breaker)?

Предыдущий опыт не требуется. Microservices Communication Patterns (Saga, Circuit Breaker) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Проектирование Саг на основе событий»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Microservices Communication Patterns (Saga, Circuit Breaker)?

Да. Каждый урок Microservices Communication Patterns (Saga, Circuit Breaker) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Проектирование Саг на основе событий
  2. Шина событий и брокеры сообщений
  3. Обработка компенсаций с помощью событий
  4. Создание идемпотентных потребителей событий
← Назад к Microservices Communication Patterns (Saga, Circuit Breaker)