DynamoDB 與 EventBridge

🔥 Vibe Prompt

「設計 DynamoDB 單表設計模式。使用 EventBridge 進行跨服務事件通訊。」

DynamoDB 單表設計

# 單表設計:多個實體共用一個表
# PK: ENTITY#ID, SK: ENTITY#METADATA

table.put_item(Item={
    'PK': 'USER#user123',
    'SK': 'PROFILE',
    'name': 'Alice',
    'email': 'alice@example.com'
})

table.put_item(Item={
    'PK': 'USER#user123',
    'SK': 'ORDER#ord456',
    'order_id': 'ord456',
    'total': 99.99,
    'status': 'pending'
})

# 查詢使用者的所有訂單
response = table.query(
    KeyConditionExpression='PK = :pk AND begins_with(SK, :sk)',
    ExpressionAttributeValues={
        ':pk': 'USER#user123',
        ':sk': 'ORDER#'
    }
)

存取模式

| 模式 | 查詢方式 | |------|---------| | 依 ID 取得使用者 | PK=USER#id, SK=PROFILE | | 取得使用者訂單 | PK=USER#id, SK begins_with ORDER# | | 取得所有使用者 | GSI 依實體類型 | | 依狀態查詢訂單 | GSI 依狀態 |

EventBridge

resource "aws_eventbridge_rule" "order_created" {
  name = "order-created"
  event_pattern = jsonencode({
    source = ["myapp.orders"]
    detail-type = ["OrderCreated"]
  })
}

resource "aws_eventbridge_target" "notification" {
  rule = aws_eventbridge_rule.order_created.name
  arn = aws_lambda_function.notification.arn
}
import boto3, json
eventbridge = boto3.client('events')

eventbridge.put_events(Entries=[{
    'Source': 'myapp.orders',
    'DetailType': 'OrderCreated',
    'Detail': json.dumps({
        'order_id': 'ord456',
        'user_id': 'user123',
        'total': 99.99
    }),
    'EventBusName': 'default'
}])

事件驅動的優點

  • 服務解耦
  • 非同步處理(有彈性)
  • 易於擴展(新增消費者)
  • 內建重試與 DLQ

本章總結

  • 理解核心概念與原理
  • 掌握實作方法與技巧
  • 熟悉常見問題與解決方案
  • 能夠應用於實際專案

延伸閱讀

  • 官方文件與 API 參考
  • GitHub 開源專案範例
  • 相關技術書籍與課程
  • 社群討論與技術部落格

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!