DynamoDB全局表 #

一、全局表概述 #

1.1 什么是全局表 #

全局表是一种多区域、多主复制的DynamoDB表,可在多个AWS区域间自动复制数据。

text
全局表特点:
├── 多区域部署
├── 多主复制
├── 自动数据同步
├── 低延迟访问
└── 高可用性

1.2 全局表优势 #

text
优势:
├── 全球低延迟访问
├── 灾难恢复
├── 数据本地化
├── 合规要求满足
└── 简化多区域架构

1.3 架构示意 #

text
                    ┌─────────────────┐
                    │   应用程序      │
                    └────────┬────────┘
                             │
         ┌───────────────────┼───────────────────┐
         │                   │                   │
         ▼                   ▼                   ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│  us-east-1      │ │  eu-west-1      │ │  ap-northeast-1 │
│  (美国东部)     │ │  (欧洲爱尔兰)   │ │  (亚太东京)     │
└─────────────────┘ └─────────────────┘ └─────────────────┘
         │                   │                   │
         └───────────────────┼───────────────────┘
                             │
                    双向自动复制

二、创建全局表 #

2.1 使用CLI创建 #

步骤1:创建源表

bash
aws dynamodb create-table \
  --table-name GlobalUsers \
  --attribute-definitions \
    AttributeName=UserId,AttributeType=S \
  --key-schema \
    AttributeName=UserId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --region us-east-1

步骤2:创建副本表

bash
aws dynamodb create-table \
  --table-name GlobalUsers \
  --attribute-definitions \
    AttributeName=UserId,AttributeType=S \
  --key-schema \
    AttributeName=UserId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --region eu-west-1

步骤3:创建全局表

bash
aws dynamodb create-global-table \
  --global-table-name GlobalUsers \
  --replication-group \
    RegionName=us-east-1 \
    RegionName=eu-west-1 \
  --region us-east-1

2.2 使用CloudFormation #

yaml
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  GlobalTable:
    Type: AWS::DynamoDB::GlobalTable
    Properties:
      TableName: GlobalUsers
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: UserId
          AttributeType: S
      KeySchema:
        - AttributeName: UserId
          KeyType: HASH
      Replicas:
        - Region: us-east-1
        - Region: eu-west-1
        - Region: ap-northeast-1

2.3 使用JavaScript SDK #

javascript
const { DynamoDBClient, CreateGlobalTableCommand } = require('@aws-sdk/client-dynamodb');

const client = new DynamoDBClient({ region: 'us-east-1' });

const command = new CreateGlobalTableCommand({
  GlobalTableName: 'GlobalUsers',
  ReplicationGroup: [
    { RegionName: 'us-east-1' },
    { RegionName: 'eu-west-1' },
    { RegionName: 'ap-northeast-1' }
  ]
});

await client.send(command);

三、管理全局表 #

3.1 添加副本 #

bash
aws dynamodb update-global-table \
  --global-table-name GlobalUsers \
  --replica-updates \
    '[
      {
        "Create": {
          "RegionName": "ap-southeast-1"
        }
      }
    ]' \
  --region us-east-1

3.2 删除副本 #

bash
aws dynamodb update-global-table \
  --global-table-name GlobalUsers \
  --replica-updates \
    '[
      {
        "Delete": {
          "RegionName": "eu-west-1"
        }
      }
    ]' \
  --region us-east-1

3.3 查看全局表信息 #

bash
aws dynamodb describe-global-table \
  --global-table-name GlobalUsers \
  --region us-east-1
json
{
  "GlobalTableDescription": {
    "GlobalTableName": "GlobalUsers",
    "ReplicationGroup": [
      {
        "RegionName": "us-east-1"
      },
      {
        "RegionName": "eu-west-1"
      },
      {
        "RegionName": "ap-northeast-1"
      }
    ],
    "GlobalTableStatus": "ACTIVE"
  }
}

3.4 列出全局表 #

bash
aws dynamodb list-global-tables \
  --region us-east-1

四、数据读写 #

4.1 写入数据 #

javascript
// 写入到最近的区域
const client = new DynamoDBClient({ region: 'ap-northeast-1' });
const docClient = DynamoDBDocumentClient.from(client);

await docClient.send(new PutCommand({
  TableName: 'GlobalUsers',
  Item: {
    UserId: 'user123',
    Name: 'John Doe',
    Email: 'john@example.com',
    Region: 'ap-northeast-1'
  }
}));

4.2 读取数据 #

javascript
// 从最近的区域读取
const response = await docClient.send(new GetCommand({
  TableName: 'GlobalUsers',
  Key: { UserId: 'user123' }
}));

4.3 冲突解决 #

text
冲突解决策略:
├── 最后写入者胜出
├── 基于时间戳
├── 自动解决
└── 应用层可自定义

五、全局表特性 #

5.1 复制延迟 #

text
复制延迟:
├── 通常小于1秒
├── 受网络影响
├── 跨区域传输
└── 最终一致性

5.2 容量管理 #

text
容量管理:
├── 每个副本独立配置
├── 按需模式自动扩展
├── 预置模式需单独配置
└── Auto Scaling支持

5.3 索引支持 #

text
索引支持:
├── GSI自动复制
├── LSI自动复制
├── 所有副本索引一致
└── 索引更新自动同步

六、使用场景 #

6.1 全球应用 #

javascript
// 根据用户位置选择区域
function getClientForRegion(userRegion) {
  const regionMap = {
    'us-east': 'us-east-1',
    'eu-west': 'eu-west-1',
    'ap-northeast': 'ap-northeast-1'
  };
  
  const region = regionMap[userRegion] || 'us-east-1';
  
  return DynamoDBDocumentClient.from(
    new DynamoDBClient({ region })
  );
}

// 使用示例
const client = getClientForRegion(user.location);
await client.send(new GetCommand({
  TableName: 'GlobalUsers',
  Key: { UserId: user.id }
}));

6.2 灾难恢复 #

javascript
// 健康检查和故障转移
async function getWithFailover(userId) {
  const regions = ['us-east-1', 'eu-west-1', 'ap-northeast-1'];
  
  for (const region of regions) {
    try {
      const client = getClientForRegion(region);
      const response = await client.send(new GetCommand({
        TableName: 'GlobalUsers',
        Key: { UserId: userId }
      }), {
        timeout: 1000  // 1秒超时
      });
      
      if (response.Item) {
        return response.Item;
      }
    } catch (error) {
      console.log(`Region ${region} failed:`, error.message);
      continue;
    }
  }
  
  throw new Error('All regions failed');
}

6.3 数据本地化 #

javascript
// 根据合规要求存储数据
async function putWithCompliance(userId, data, requiredRegion) {
  const client = getClientForRegion(requiredRegion);
  
  await client.send(new PutCommand({
    TableName: 'GlobalUsers',
    Item: {
      UserId: userId,
      ...data,
      StoredRegion: requiredRegion,
      CreatedAt: new Date().toISOString()
    }
  }));
}

七、监控全局表 #

7.1 CloudWatch指标 #

text
关键指标:
├── ReplicationLatency
│   └── 复制延迟
├── WriteProvisionedThroughputExceeded
│   └── 写入限流
├── SystemErrors
│   └── 系统错误
└── UserErrors
    └── 用户错误

7.2 监控示例 #

javascript
// 监控复制延迟
const { CloudWatchClient, GetMetricStatisticsCommand } = require('@aws-sdk/client-cloudwatch');

const cloudwatch = new CloudWatchClient({ region: 'us-east-1' });

async function getReplicationLatency(tableName, region) {
  const response = await cloudwatch.send(new GetMetricStatisticsCommand({
    Namespace: 'AWS/DynamoDB',
    MetricName: 'ReplicationLatency',
    Dimensions: [
      { Name: 'TableName', Value: tableName },
      { Name: 'ReceivingRegion', Value: region }
    ],
    StartTime: new Date(Date.now() - 3600000),
    EndTime: new Date(),
    Period: 300,
    Statistics: ['Average', 'Maximum']
  }));
  
  return response.Datapoints;
}

八、最佳实践 #

8.1 区域选择 #

text
区域选择建议:
├── 选择靠近用户的区域
├── 考虑合规要求
├── 评估网络延迟
├── 考虑成本因素
└── 最少2个区域

8.2 冲突处理 #

text
冲突处理建议:
├── 使用时间戳解决冲突
├── 设计幂等操作
├── 避免并发更新同一项目
├── 使用条件写入
└── 应用层冲突解决

8.3 性能优化 #

text
性能优化建议:
├── 使用按需容量模式
├── 监控复制延迟
├── 优化项目大小
├── 合理设计分区键
└── 避免热点分区

九、限制与注意事项 #

9.1 限制 #

text
全局表限制:
├── 每个全局表最多50个副本
├── 不支持跨账户复制
├── 不支持LSI(仅GSI)
├── 必须使用按需或预置容量
└── 不支持条件表达式的某些功能

9.2 注意事项 #

text
注意事项:
├── 复制延迟可能导致读取旧数据
├── 冲突解决基于时间戳
├── 删除操作会复制到所有副本
├── 表更新需要时间传播
└── 成本随副本数量增加

十、总结 #

全局表要点:

特性 说明
多区域 支持多个AWS区域
多主复制 所有副本可读写
自动同步 数据自动复制
冲突解决 最后写入者胜出
延迟 通常<1秒

下一步,让我们学习备份与恢复!

最后更新:2026-03-27