ElastiCache Redis 复制组与集群模式
构建 Redis 复制组以扩展读取能力,并启用集群模式,将数据分片到多个节点组中
ElastiCache Redis 复制组与集群模式 是 CoddyKit 上的免费 Cloud & IT Cert Prep 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Cloud & IT Cert Prep 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Cloud & IT Cert Prep 课程共包含 4 节课。
Redis 复制组概述
一个 ElastiCache Replication Group 是由一个 Redis 主节点和最多 5 个只读副本组成的逻辑分组。主节点处理所有写入操作;副本从主节点接收异步复制,并处理读取流量。复制组支持两项关键能力:读取扩展(在多个副本之间分发读取请求)以及通过自动故障转移实现高可用性(主节点发生故障时将副本提升为主节点)。复制组中的所有节点共享同一数据集。
# Create a replication group with 1 primary and 2 read replicas
aws elasticache create-replication-group \
--replication-group-id web-cache \
--replication-group-description 'Web application cache' \
--num-cache-clusters 3 \
--cache-node-type cache.r7g.large \
--engine redis \
--engine-version '7.0' \
--automatic-failover-enabled \
--multi-az-enabled \
--cache-subnet-group-name my-multi-az-subnet-group主端点与读取端点
ElastiCache 为复制组提供两个 DNS 端点:主端点始终指向当前主节点(故障转移期间会自动更新),用于所有写入操作;读取端点会在所有可用副本之间进行读取请求的负载均衡,用于读取操作以分散负载。您的应用应维护两个连接池:一个连接到主端点以执行写入,另一个连接到读取端点以执行读取。这是 ElastiCache Redis 复制组推荐的连接模式。
# Get primary and reader endpoints
aws elasticache describe-replication-groups \
--replication-group-id web-cache \
--query 'ReplicationGroups[].{
Primary:NodeGroups[].PrimaryEndpoint.Address,
Reader:ReaderEndpoint.Address
}'
# Application connection pattern:
# write_client = redis.Redis(host='primary-endpoint', port=6379)
# read_client = redis.Redis(host='reader-endpoint', port=6379)自动故障转移过程
当主节点发生故障时(ElastiCache 会通过运行状况检查在数秒内检测到故障),自动故障转移会选择一个只读副本并将其提升为主节点。提升过程如下:(1)选定的副本被提升为主节点;(2)主端点 DNS 记录更新为指向新的主节点(TTL 约为 1 秒);(3)旧主节点被新的副本替换。整个故障转移过程通常需要 30 至 60 秒。使用主端点 DNS的应用会在 DNS 传播后自动重新连接,无需硬编码 IP 地址。
# Test failover manually (triggers primary failover)
aws elasticache test-failover \
--replication-group-id web-cache \
--node-group-id 0001
# Monitor failover events
aws elasticache describe-events \
--source-identifier web-cache \
--source-type replication-group \
--duration 60 \
--query 'Events[].{Time:Date,Message:Message}'Multi-AZ 副本放置
为了获得最大的恢复能力,请将副本分布在多个可用区中。在复制组上启用 Multi-AZ 后,ElastiCache 会自动将主节点和副本放置在不同的 AZ 中。如果整个 AZ 下线,故障转移会将某个仍可用 AZ 中的副本提升为主节点。创建复制组时,您也可以使用 --preferred-cache-cluster-a-zs 选项,明确指定每个节点的首选 AZ。
# Create replication group with explicit AZ placement
aws elasticache create-replication-group \
--replication-group-id ha-redis \
--replication-group-description 'Multi-AZ Redis' \
--num-cache-clusters 3 \
--cache-node-type cache.r7g.xlarge \
--engine redis \
--automatic-failover-enabled \
--multi-az-enabled \
--preferred-cache-cluster-a-zs us-east-1a us-east-1b us-east-1c \
--cache-subnet-group-name multi-az-subnets什么是 Redis 集群模式
Redis Cluster Mode Enabled (CME) 会将数据集分区到多个节点组(分片)中,每个节点组包含一个主节点和最多 5 个副本。这是 Redis 的水平分片解决方案。集群模式允许您突破单个节点的内存限制:最多可以拥有 500 个节点组,每个节点组容量为 500 GB,这意味着单个 Redis 集群最多可以存储 500 × 500 GB = 250 TB 的数据。集群模式还可以提高写入吞吐量,因为每个节点组都会独立处理其负责的键范围内的写入操作。
# Create a Redis Cluster Mode Enabled replication group
# with 3 shards, each with 1 primary and 2 replicas
aws elasticache create-replication-group \
--replication-group-id clustered-redis \
--replication-group-description 'Cluster mode: 3 shards x 3 nodes' \
--num-node-groups 3 \
--replicas-per-node-group 2 \
--cache-node-type cache.r7g.large \
--engine redis \
--automatic-failover-enabled \
--multi-az-enabled \
--cache-subnet-group-name multi-az-subnets哈希槽与键分布
Redis 集群模式将键空间划分为 16,384 个哈希槽。每个节点组拥有一段连续的哈希槽范围。写入某个键时,Redis 会计算 CRC16(key) % 16384,以确定哈希槽以及负责该槽的节点组。您的应用必须使用支持集群的 Redis 客户端(例如 redis-py-cluster,或集群模式下的 Jedis),该客户端需要了解槽位映射,并将每条命令路由到正确的节点。标准客户端如果将键发送到错误的分片,将返回 MOVED 重定向错误。
# Python cluster-aware client example
# pip install redis[hiredis]
# from redis.cluster import RedisCluster
# cluster_client = RedisCluster(
# host='clustered-redis.abc123.clustercfg.use1.cache.amazonaws.com',
# port=6379,
# decode_responses=True
# )
# The client automatically resolves slot-to-node mapping
# cluster_client.set('user:1', 'Alice') # routes to correct shard
# cluster_client.get('user:1') # routes to correct shard集群模式与非集群模式
在 SAA-C03 考试中,出现以下情况时请选择非集群模式:数据可以存放在单个节点上(预留余量后小于约 400 GB)、需要简单的主节点/副本设置,或应用使用复杂的多键操作(跨多个键的事务要求所有键位于同一个槽中)。出现以下情况时请选择集群模式:数据集超过单个节点的内存容量、需要水平扩展写入吞吐量,或预计未来增长将要求在线重新分片。集群模式支持在不中断服务的情况下添加分片(在线重新分片)。
# Scale out a cluster-mode Redis by adding shards
aws elasticache modify-replication-group-shard-configuration \
--replication-group-id clustered-redis \
--node-group-count 5 \
--apply-immediately \
--resharding-configuration \
NodeGroupId=0004,PreferredAvailabilityZones=us-east-1a,us-east-1b,us-east-1c \
NodeGroupId=0005,PreferredAvailabilityZones=us-east-1a,us-east-1b,us-east-1c
# No downtime — slots are migrated incrementally用于跨区域复制的 Global Datastore
ElastiCache Global Datastore 将 Redis 复制扩展到多个 AWS 区域。您可以指定一个区域作为主集群,并在其他区域添加辅助集群。写入操作发送到主集群;辅助集群通过异步复制接收数据,通常延迟低于 1 秒。辅助集群可以为本地读取提供极低的延迟。Global Datastore 支持全球应用程序:不同大洲的用户可以从距离最近的区域读取数据;同时也支持跨区域 DR,当主区域发生故障时,您可以将某个辅助集群提升为主集群。
# Create a Global Datastore (adds a secondary region to an existing cluster)
aws elasticache create-global-replication-group \
--global-replication-group-id-suffix my-global-cache \
--primary-replication-group-id prod-redis
# Add a secondary cluster in another region
aws elasticache create-replication-group \
--replication-group-id prod-redis-eu \
--replication-group-description 'EU secondary' \
--global-replication-group-id ldgnf-my-global-cache \
--region eu-west-1大规模 Redis 发布/订阅
在非集群 Redis 复制组中,发布/订阅消息会分发给所有副本——任何节点上的订阅者都可以接收发布到某个频道的消息。但是,在集群模式下,发布/订阅仅限于键空间通知,基于频道的发布/订阅只能在单个分片内工作,除非您使用支持 Redis 7 及更高版本的发布/订阅分片(使用 SSUBSCRIBE / SPUBLISH 实现支持分片感知的发布/订阅)。在使用集群模式设计大规模发布/订阅时,这是一个重要限制。
# Keyspace notification (fires when a key expires)
# Enable in parameter group: notify-keyspace-events Ex
# Subscriber in Python:
# pubsub = redis_client.pubsub()
# pubsub.psubscribe('__keyevent@0__:expired')
# for message in pubsub.listen():
# if message['type'] == 'pmessage':
# expired_key = message['data']
# print(f'Key expired: {expired_key}')监控复制延迟
监控只读副本上的 ReplicationLag CloudWatch 指标,以确保它们能够跟上主集群。延迟超过几秒通常表示副本存在瓶颈(节点过载、网络问题,或写入量超过副本的处理能力)。在 Global Datastore 场景中,请监控 GlobalDatastoreReplicationLag。较高的复制延迟意味着只读副本可能返回过期数据——对于要求在严格范围内实现最终一致性的应用程序来说,这一点非常重要。
# Monitor replication lag for all replicas
aws cloudwatch get-metric-statistics \
--namespace AWS/ElastiCache \
--metric-name ReplicationLag \
--dimensions Name=ReplicationGroupId,Value=web-cache \
--statistic Maximum \
--period 60 \
--start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ)
# Alert if ReplicationLag > 10 seconds扩展复制组
您可以进行垂直扩展(更改节点类型),也可以进行水平扩展(添加或删除副本)。更改节点类型需要调用 modify-replication-group,并且在立即应用更改时会导致短暂的故障转移——主节点会被替换为新类型的节点。添加副本可以在线完成,不会造成停机。从非集群模式扩展到集群模式时,您必须创建新的集群模式组并迁移数据——集群模式与非集群模式之间无法进行原地转换。
# Scale up node type with maintenance window
aws elasticache modify-replication-group \
--replication-group-id web-cache \
--cache-node-type cache.r7g.xlarge \
--apply-immediately false
# Add a read replica
aws elasticache increase-replica-count \
--replication-group-id web-cache \
--new-replica-count 4 \
--apply-immediately快速检查
请测试您对本课 AWS 解决方案架构师(SAA-C03)相关概念的理解。
课程回顾
本课介绍了以下内容:复制组通过副本提供读取扩展,并通过带有主节点/读取器端点的自动故障转移提供高可用性;集群模式使用 16,384 个哈希槽,将数据分布到最多 500 个节点组中,从而突破单个节点内存的限制进行水平扩展;Global Datastore跨区域复制数据,为全球用户提供低延迟读取和跨区域 DR。接下来,我们将介绍缓存策略:Lazy Loading 和写入直通。
常见问题解答
「ElastiCache Redis 复制组与集群模式」课时是免费的吗?
是的 — 「ElastiCache Redis 复制组与集群模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Cloud & IT Cert Prep 课程的其余内容,请升级到 CoddyKit PRO。 Cloud & IT Cert Prep 课程共包含 4 节课。
「ElastiCache Redis 复制组与集群模式」这节课中我会学到什么?
构建 Redis 复制组以扩展读取能力,并启用集群模式,将数据分片到多个节点组中 你通过在浏览器中直接运行的动手代码来练习 Cloud & IT Cert Prep,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Cloud & IT Cert Prep 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Cloud & IT Cert Prep 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「ElastiCache Redis 复制组与集群模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Cloud & IT Cert Prep 课中编写并运行代码吗?
能。每节 Cloud & IT Cert Prep 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Redis 与 Memcached:选择合适的引擎
- ElastiCache Redis 复制组与集群模式
- 缓存策略:延迟加载与写入直达
- 会话存储与排行榜模式