microservices
Микросервисы и процесс взаимодействия
Паттерны и best practices для организации взаимодействия между микросервисами
•
#microservices
#communication
#patterns
#architecture
Микросервисы и процесс взаимодействия
Эффективное взаимодействие между микросервисами — ключевой аспект успешной распределенной системы.
Типы взаимодействия
Синхронное (REST/gRPC)
class OrderService {
async createOrder(orderData: CreateOrderDto) {
// Проверка инвентаря
const available = await this.inventoryClient.check(orderData.items);
if (!available) throw new Error('Items not available');
// Создание заказа
const order = await this.repository.save(orderData);
// Обработка платежа
await this.paymentClient.process(order);
return order;
}
}
Асинхронное (Events/Messages)
class OrderService {
async createOrder(orderData: CreateOrderDto) {
const order = await this.repository.save(orderData);
// Публикуем событие
await this.eventBus.publish('order.created', order);
return order;
}
}
Saga Pattern
class OrderSaga {
async execute(orderData: CreateOrderDto) {
const compensations = [];
try {
const order = await this.orderService.create(orderData);
compensations.push(() => this.orderService.cancel(order.id));
await this.inventoryService.reserve(order.items);
compensations.push(() => this.inventoryService.release(order.items));
await this.paymentService.process(order);
return order;
} catch (error) {
for (const compensate of compensations.reverse()) {
await compensate();
}
throw error;
}
}
}
Circuit Breaker
class CircuitBreaker {
private failures = 0;
private state = 'CLOSED';
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === 'OPEN') {
throw new Error('Circuit breaker is OPEN');
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
}
API Gateway
class APIGateway {
async getOrderDetails(orderId: string) {
const [order, customer, shipping] = await Promise.all([
this.orderService.getOrder(orderId),
this.customerService.getCustomer(customerId),
this.shippingService.getShipment(orderId)
]);
return { order, customer, shipping };
}
}
Best Practices
- Используйте асинхронное взаимодействие — где возможно
- Применяйте timeout и retry — для устойчивости
- Реализуйте Circuit Breaker — защита от каскадных сбоев
- Идемпотентность — операции должны быть безопасны для повтора
- Версионирование API — для обратной совместимости
- Мониторинг — отслеживайте все взаимодействия
Заключение
Правильная организация взаимодействия между микросервисами обеспечивает надежность и масштабируемость всей системы.