Triển khai Saga Pattern trong microservices với NodeJS và Choreography-Based Saga
Bài viết được sự cho phép của tác giả Duy Phan
Mình sẽ sử dụng lại ví dụ Booking Service Online trong phần trước đó
Ở đây mình sẽ tạo ra các isolated service, đồng thời thiết kế để chúng giao tiếp với nhau thông qua một Message Queue. Ở đây mình chọn RabbitMQ làm Message Queue.
1. Triển khai BookingService
// booking-service.ts
import express from 'express'
import amqp from 'amqplib'
const app = express()
const PORT = 3001
app.use(express.json())
let channel: amqp.Channel
const paymentQueue = 'payment_queue'
app.post('/booking', async (req, res) => {
  const { userId, eventId, numberOfSeats } = req.body
  // Pre-step 1: Validate booking request
  // Pre-step 2: Save booking request to application database
  const booking = {
    userId,
    eventId,
    numberOfSeats,
    bookingReservedSuccessfully: true,
  }
  /**
   * Step 1: Send Booking Request to PaymentService
   */
  if (booking.bookingReservedSuccessfully) {
    await sendMessageToQueue(paymentQueue, { booking })
  }
  res.json({ message: 'Booking request sent successfully' })
})
async function connectQueue(queue: string) {
  const connection = await amqp.connect('amqp://localhost')
  channel = await connection.createChannel()
  await channel.assertQueue(queue)
}
async function sendMessageToQueue(queue: string, message: unknown) {
  await channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)))
}
app.listen(PORT, async () => {
  console.log(`BookingService is running on http://localhost:${PORT}`)
  await connectQueue(paymentQueue)
})
BookingService xử lý các yêu cầu HTTP POST để tạo booking mới. BookingService cố gắng đặt trước một chỗ và nếu thành công, nó sẽ gửi mộ [...]
Read more