aws 数据库
1. RDS
1
2
3
|
https://docs.aws.amazon.com/zh_cn/cli/latest/userguide/cli_rds_code_examples.html
https://docs.aws.amazon.com/zh_cn/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.CommonTasks.html
https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-cluster.html
|
注意区分集群 和 实例
postgresql
注意事项
参数组参数
1
|
rds.force_ssl 1 # 默认值为 1, 需要 ssl 访问, 需要下载证书
|
创建一个实例
1
2
3
4
5
6
7
|
aws rds create-db-cluster \
--db-cluster-identifier sample-pg-cluster \
--engine aurora-postgresql \
--master-username master \
--master-user-password secret99 \
--db-subnet-group-name default \
--vpc-security-group-ids sg-0b9130572daf3dc16
|
连接地址
sample-pg-cluster.xxxxxxx.ap-southeast-1.rds.amazonaws.com
性能指标
Total DB load 47.03 表示数据库的总负载, 即所有活动和等待事件的总和
CPU 13.88, 30% CPU 使用占总负载的百分比;
IO:DataFileRead 3.45, 7%
从数据文件读取操作占总负载的百分比; 这反映了数据库从磁盘读取数据文件的频率和资源消耗
mysql
1
2
3
4
5
6
7
|
# 查询 MySQL 可用版本
aws rds describe-db-engine-versions --engine mysql --query "DBEngineVersions[].EngineVersion"
# 查询 aurora 可用版本
aws rds describe-db-engine-versions --engine aurora --query "DBEngineVersions[].EngineVersion"
aws rds describe-db-engine-versions --engine aurora-mysql --query "DBEngineVersions[].EngineVersion"
|
- 创建集群
- 创建实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# 创建集群, 注意返回信息中的 endpoint 地址
aws rds create-db-cluster \
--db-cluster-identifier cluster01 \
--engine aurora-mysql \
--engine-version 5.7 \
--master-username admin \
--master-user-password secret99 \
--db-subnet-group-name default \
--vpc-security-group-ids sg-0b9130572daf3dc16
# 其它参数
--kms-key-id b43c75aa-bb7d-481d-94e0-8bc45401bd36
--storage-encrypted
--enable-cloudwatch-logs-exports '["audit","error","general","slowquery"]'
# 创建实例
# 返回结果中也包含一个 endpoint, 但这个地址是写入节点本机的, 不是集群地址, 不具备高可用能力
aws rds create-db-instance \
--db-instance-identifier cluster01 \
--db-instance-class db.t3.micro \
--engine mysql \
--master-username admin \
--master-user-password secret99 \
--allocated-storage 20
|
其它管理命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
aws rds create-db-parameter-group \
--db-parameter-group-name mydbparametergroup \
--db-parameter-group-family MySQL5.6 \
--description "My new parameter group"
aws rds create-db-snapshot \
--db-instance-identifier database-mysql \
--db-snapshot-identifier mydbsnapshot
# 创建集群 - 读副本
aws rds create-db-instance-read-replica \
--db-instance-identifier test-instance-repl \
--source-db-instance-identifier test-instance
# 使用 AWS CLI 创建只读副本
aws rds create-db-instance-read-replica \
--db-instance-identifier my-db-read-replica \
--source-db-instance-identifier my-primary-db \
--db-instance-class db.t3.medium \
--availability-zone us-east-1a
# 修改实例配置
aws rds modify-db-instance
|
cli manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
# 查看集群详细信息
aws rds describe-db-clusters --db-cluster-identifier mydbcluster
# 查看实例详细信息
aws rds describe-db-instances --db-instance-identifier mydbinstancecf
# 查看指定 RDS 数据库实例最近发生的事件列表
aws rds describe-events --source-identifier test-instance --source-type db-instance
# delete
# 在删除之前, 自动创建一个数据库快照
aws rds delete-db-instance --db-instance-identifier test-instance \
--final-db-snapshot-identifier test-instance-final-snap
# 获取性能指标数据, 参数存储在 JSON 文件中
aws pi get-resource-metrics --service-type RDS --identifier db-LKCGOBK26374TPTDFXOIWVCPPM \
--start-time 1527026400 --end-time 1527080400 --period-in-seconds 300 \
--metric db.load.avg --metric-queries file://metric-queries.json
metric-queries.json
[
{
"Metric": "db.load.avg",
"GroupBy": {
"Group":"db.wait_event"
}
}
]
|
2. RDS Proxy
创建 RDS Proxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
aws rds create-db-proxy \
--db-proxy-name my-db-proxy \
--engine-family MYSQL \
--role-arn arn:aws:iam::123456789012:role/rds-proxy-role \
--vpc-subnet-ids subnet-123456 subnet-789012 \
--auth UsernamePassword \
--secret-arn arn:aws:secretsmanager:us-east-1:123456789012:secret:my-db-credentials
aws rds create-db-proxy \
--db-proxy-name my-rds-proxy \
--engine-family MYSQL \
--auth-type SECRETS \
--require-tls \
--idle-client-timeout 1800 \
--debug-logging \
--role-arn arn:aws:iam::123456789012:role/RDSProxyRole \
--vpc-subnet-ids subnet-12345678 subnet-87654321 \
--vpc-security-group-ids sg-12345678 \
--auth Description="RDS Proxy Auth",AuthScheme=SECRETS,IAMAuth=DISABLED,SecretArn=arn:aws:secretsmanager:us-east-1:123456789012:secret:rds-proxy-credentials-ABC123
|
1
2
3
4
5
6
7
|
# 添加主数据库作为写端点
aws rds register-db-proxy-targets --db-proxy-name my-rds-proxy --target-group-name default \
--db-instance-identifier my-primary-db
# 添加只读副本作为读端点
aws rds register-db-proxy-targets --db-proxy-name my-rds-proxy --target-group-name reader \
--db-instance-identifier my-read-replica-1
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 检查复制状态
aws rds describe-db-instances \
--db-instance-identifier my-read-replica \
--query 'DBInstances[0].{Status:DBInstanceStatus, ReplicaStatus:StatusInfos[0].Status}'
# 监控 CloudWatch 指标
aws cloudwatch get-metric-statistics \
--namespace AWS/RDS \
--metric-name ReplicaLag \
--dimensions Name=DBInstanceIdentifier,Value=my-read-replica \
--start-time $(date -u -d "5 minutes ago" +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 60 \
--statistics Maximum
|
1
2
3
4
5
6
7
8
|
# 查看代理状态
aws rds describe-db-proxies --db-proxy-name my-rds-proxy
# 查看目标状态
aws rds describe-db-proxy-targets --db-proxy-name my-rds-proxy
# 查看代理日志
aws rds describe-db-proxy-log-files --db-proxy-name my-rds-proxy
|
3. DynamoDB
一种 NoSQL 数据库服务, 使用键值对来存储数据
无模式(Schema-less)的; 同一张表中的不同项可以拥有完全不同的属性集合
数据结构层级
Table 表: 与其他数据库类似, 是数据的集合容器;
与关系型数据库不同的是, DynamoDB 在创建表时只需定义主键(Primary Key),
无需预先定义其他列或属性(Schema-less);
Item 项: 表中的一条数据记录, 类似于关系型数据库中的"行(Row)"
Attribute 属性: 组成项的基本数据单元, 类似于"列(Column)", 但 DynamoDB 支持嵌套结构
数据类型标识
用于告诉 DynamoDB 该属性的具体类型
| 标识符 |
数据类型 |
描述与示例 |
| S |
String |
区分大小写的字符串; 例如: {“S”: “张三”} |
| N |
Number |
整数或小数, 作为字符串传输; 例如: {“N”: “99.9”} |
| B |
Binary |
二进制数据(Base64 编码); 例如: {“B”: “dGVzdA==”} |
| BOOL |
Boolean |
布尔值; 例如: {“BOOL”: true} |
| NULL |
Null |
表示空值; 例如: {“NULL”: true} |
| L |
List |
存储有序的集合, 类型可混合; 例如: {“L”: [{“S”: “apple”}, {“N”: “5”}]} |
| M |
Map |
存储无序的键值对集合, 类似 JSON 对象; |
| SS |
Set |
字符串集合, 元素必须唯一 |
| NS |
Set |
数字集合, 元素必须唯一 |
| BS |
Set |
二进制集合, 元素必须唯一 |
1
|
Map : {"M": {"name": {"S": "李四"}, "age": {"N": "18"}}}
|
map 和 list 可以构建深度最多 32 层的复杂 JSON 结构
Primary Key 主键
分区键(Partition Key)
必须存在, DynamoDB 根据该值的哈希值进行物理存储分布;
选择分区键时, 建议选择基数大(取值种类多)的属性(如 user_id), 避免出现"热点"分区;
排序键(Sort Key)
可选, 用于在同一分区键下对数据进行排序;
支持字符串(S), 数字(N)或二进制(B)类型;
如果业务存在"一对多"查询需求(如查询"某用户的所有订单"), 建议将关联属性设计为排序键;
管理 cli
- 使用 CLI 操作时, 必须显式声明类型
- 使用语言 SDK 时, 通常会字段解决类型声明;
管理表
1
2
3
|
# 列出全部表
aws --profile uat --region us-east-1 dynamodb list-tables
|
数据查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
# 必须同时指定分区键和排序键
aws --profile uat --region us-east-1 \
dynamodb get-item \
--table-name Riv-Prod-SharedStorageMetadataFaceTable609BE09F-16WEOJN0II315 \
--key '{"PartitionKey": {"S": "User::84e571c1-d0f9-49ce-b797-581c7542ac9b"}, "SortKey": {"S": "Face::1909665b-73dc-48a9-9bba-40725105c633"}}' \
--return-consumed-capacity TOTAL
# 扫描表里面的全部数据
aws --profile uat --region us-east-1 dynamodb scan \
--table-name Riv-Prod-SharedStorageMetadataFaceTable609BE09F-16WEOJN0II315
# 扫描表里面的全部数据 - 过滤
aws --profile uat --region us-east-1 dynamodb scan \
--table-name Riv-Prod-SharedStorageMetadataFaceTable609BE09F-16WEOJN0II315 \
--filter-expression "PartitionKey = :a" \
--expression-attribute-values '{":a":{"S":"User::ae6bd981-409e-4651-b88c-dab9ee06bdd3"}}' \
--return-consumed-capacity TOTAL
# 文件搜索 key
# awskey.json
{"PartitionKey": {"S": "User::84e571c1-d0f9-49ce-b797-581c7542ac9b"}}
aws --profile zhongtai --region us-east-1 dynamodb scan \
--table-name Riv-Prod-SharedStorageMetadataFaceTable609BE09F-7A7RS2GQO97O \
--filter-expression "PartitionKey = :a" \
--expression-attribute-values '{":a":{"S":"User::ae6bd981-409e-4651-b88c-dab9ee06bdd3"}}' \
--return-consumed-capacity TOTAL
|
数据
1
2
3
4
5
6
7
8
9
10
11
|
{
"user_id": {"S": "user_001"},
"age": {"N": "25"},
"tags": {"SS": ["developer", "aws"]},
"profile": {
"M": {
"city": {"S": "上海"},
"score": {"N": "88.5"}
}
}
}
|
python sdk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your_table_name')
# 检查主键名
primary_key = table.key_schema[0]['AttributeName']
if primary_key != 'your_primary_key':
raise ValueError("提供的键名与定义的键名不匹配")
# 检查排序键名
sort_key = table.key_schema[1]['AttributeName']
if sort_key != 'your_sort_key':
raise ValueError("提供的键名与定义的键名不匹配")
# 可以使用 Table.attribute_definitions 属性来获取 DynamoDB 表的键值类型信息
# 检查主键值类型
primary_key_type = table.attribute_definitions[0]['AttributeType']
if type(your_primary_key) != primary_key_type:
raise TypeError("提供的键值与定义的键值类型不匹配")
# 检查排序键值类型
sort_key_type = table.attribute_definitions[1]['AttributeType']
if type(your_sort_key) != sort_key_type:
raise TypeError("提供的键值与定义的键值类型不匹配")
|
DMS
数据库迁移服务
注意内部是通过触发器进行同步的, 触发器的用户和相关权限需要注意
因为数据迁移用过一次, 因为触发器引发业务 bug, 所以又放弃使用了;
pg 数据库
1
2
3
|
-- 独立的迁移用户需要有相关权限
GRANT rds_superuser to your_user;
GRANT rds_replication to your_user;
|
蓝绿部署
用于版本升级阶段
蓝是旧环境, 绿是新环境
传统原地升级方式停机时间在 10 分钟以上;
特点:
- 停机时间秒级别, 一般 30s-60s;
- 切换完成后, 原实例的 endpoint/CNAME 保持不变, 应用无需修改连接字符串
前提: 蓝绿部署要求源实例启用自动备份
流程
- 创建新版本参数组, 选择新版本引擎
- 创建升级前快照
- 选择数据库实例, 创建蓝绿部署, 填一个部署名称
- 源实例: 选择自动填充选中的实例
- 目标引擎版本: 新版本
- 目标参数组: 新创建的参数组
- 其它: 自定义绿实例的配置规格信息
- 完成
- 查看和等待蓝绿部署状态 AVAILABLE
部署将自动处理 创建实例, 数据同步复制, 设置备份策略等;
按数据量大小, 一般在 20 分钟至数小时;
业务测试和应用连接验证, 此时绿库是只读的;
切换阶段
- RDS 控制台 → 蓝绿部署 → 选择部署 → 操作 → 切换蓝绿部署
- 填写切换超时时间(建议保持默认 300 秒)
- 完成
- 等待确认部署的状态改变为 SWITCHOVER_COMPLETED
业务验证
清理资源 - 一般等1天或数天后再清理
- 直接删除"蓝绿部署"资源
- 删除当前的 绿 实例
回滚方案:
- 方法 1: 再次执行蓝绿切换, 切回旧实例
- 方法 2: 修改应用连接指向旧实例
- 方法 3: 从快照恢复一个实例
相关 cli
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# 查看实例当前版本
aws rds describe-db-instances \
--db-instance-identifier xxxx \
--query 'DBInstances[0].{Status:DBInstanceStatus,Version:EngineVersion,MultiAZ:MultiAZ}' \
--region xxx
# 创建快照
aws rds create-db-snapshot \
--db-instance-identifier xxxx\
--db-snapshot-identifier pre-upgrade-snapshot-202607 \
--region xxxx
# 创建一个 蓝绿部署
aws rds create-blue-green-deployment \
--blue-green-deployment-name mysql80-to-84-upgrade \
--source arn:aws:rds:::db:\
--target-engine-version 8.4 \
--region xxx
# 查看蓝绿部署状态
aws rds describe-blue-green-deployments \
--blue-green-deployment-identifier bgd-xxxxxxxxxxxxx \
--region xxx
# 查看绿环境实例详情(实例名格式: { 源实例名 }-green-{ 随机字符 })
aws rds describe-db-instances \
--db-instance-identifier-green-xxxxx \
--query 'DBInstances[0].{Status:DBInstanceStatus,Version:EngineVersion}' \
--region xxx
# 切换
aws rds switchover-blue-green-deployment \
--blue-green-deployment-identifier bgd-xxxxxxxxxxxxx \
--switchover-timeout 300 \
--region xxx
# 删除蓝绿部署
aws rds delete-blue-green-deployment \
--blue-green-deployment-identifier bgd-xxxxxxxxxxxxx \
--region xxx
# 删除绿实例
aws rds delete-db-instance \
--db-instance-identifier-old1 \
--skip-final-snapshot \
--region xxx
# 从快照恢复一个实例
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier-rollback \
--db-snapshot-identifier pre-upgrade-snapshot-202607 \
--region xxx
|
业务基础验证
1
2
3
4
|
-- 检查复制延迟
SHOW REPLICA STATUS\G
SELECT COUNT(*) FROM t_table;
|