

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 开始使用亚马逊 ElastiCache
<a name="GettingStarted"></a>

使用本节中的动手教程来帮助您入门并了解有关使用的更多信息 ElastiCache。

**Topics**
+ [设置 ElastiCache](set-up.md)
+ [创建 Valkey 无服务器缓存](GettingStarted.serverless-valkey.step1.md)
+ [创建 Redis OSS 无服务器缓存](GettingStarted.serverless-redis.step1.md)
+ [创建 Memcached 无服务器缓存](create-serverless-cache-mem.md)
+ [教程：Python 和 ElastiCache 入门](ElastiCache-Getting-Started-Tutorials.md)
+ [教程：将 Lambda 配置为在 VPC ElastiCache 中进行访问](LambdaRedis.md)

# 设置 ElastiCache
<a name="set-up"></a>

要使用 ElastiCache Web 服务，请按照以下步骤操作。

**Topics**
+ [注册获取AWS 账户](#sign-up-for-aws)
+ [创建具有管理访问权限的用户](#create-an-admin)
+ [授权以编程方式访问](#elasticache-set-up-access-key)
+ [设置权限](#elasticache-set-up-permissions)
+ [设置 EC2](#elasticache-install-configure-ec2)
+ [授予网络访问权限](#elasticache-install-grant-access-VPN)
+ [设置命令行访问权限](#Download-and-install-cli)

## 注册获取AWS 账户
<a name="sign-up-for-aws"></a>

如果您没有AWS 账户，请完成以下步骤来创建一个。

**报名参加AWS 账户**

1. 打开[https://portal.aws.amazon.com/billing/注册。](https://portal.aws.amazon.com/billing/signup)

1. 按照屏幕上的说明操作。

   在注册时，将接到电话或收到短信，要求使用电话键盘输入一个验证码。

   当您注册时AWS 账户，就会创建*AWS 账户根用户*一个。根用户有权访问该账户中的所有AWS 服务和资源。作为最佳安全实践，请为用户分配管理访问权限，并且只使用根用户来执行[需要根用户访问权限的任务](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS注册过程完成后会向您发送一封确认电子邮件。您可以随时前往 [https://aws.amazon.com/](https://aws.amazon.com/)并选择 “**我的账户”，查看您当前的账户活动并管理您的账户**。

## 创建具有管理访问权限的用户
<a name="create-an-admin"></a>

注册后，请保护您的安全AWS 账户AWS 账户根用户AWS IAM Identity Center，启用并创建管理用户，这样您就不会使用 root 用户执行日常任务。

**保护你的AWS 账户根用户**

1.  选择 **Root 用户**并输入您的AWS 账户电子邮件地址，以账户所有者的身份登录。[AWS 管理控制台](https://console.aws.amazon.com/)在下一页上，输入您的密码。

   要获取使用根用户登录方面的帮助，请参阅《AWS 登录用户指南》**中的 [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 为您的根用户启用多重身份验证（MFA）。

   有关说明，请参阅 I [A *M* 用户指南中的为AWS 账户根用户启用虚拟 MFA 设备（控制台）](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**创建具有管理访问权限的用户**

1. 启用 IAM Identity Center。

   有关说明，请参阅**《AWS IAM Identity Center用户指南》中的 [Enabling。AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)

1. 在 IAM Identity Center 中，为用户授予管理访问权限。

   有关使用IAM Identity Center 目录作为身份源的教程，请参阅《[用户*指南》IAM Identity Center 目录中的使用默认设置配置AWS IAM Identity Center用户*访问权限](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html)。

**以具有管理访问权限的用户身份登录**
+ 要使用您的 IAM Identity Center 用户身份登录，请使用您在创建 IAM Identity Center 用户时发送到您的电子邮件地址的登录 URL。

  有关使用 IAM Identity Center 用户[登录的帮助，请参阅*AWS 登录用户指南*中的登录AWS访问门户](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)。

**将访问权限分配给其他用户**

1. 在 IAM Identity Center 中，创建一个权限集，该权限集遵循应用最低权限的最佳做法。

   有关说明，请参阅《AWS IAM Identity Center用户指南》**中的 [Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 将用户分配到一个组，然后为该组分配单点登录访问权限。

   有关说明，请参阅《AWS IAM Identity Center用户指南》**中的 [Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 授权以编程方式访问
<a name="elasticache-set-up-access-key"></a>

如果用户想在AWS外部进行交互，则需要编程访问权限AWS 管理控制台。授予编程访问权限的方式取决于正在访问的用户类型AWS。

要向用户授予编程式访问权限，请选择以下选项之一。


****  

| 哪个用户需要编程式访问权限？ | 目的 | 方式 | 
| --- | --- | --- | 
| IAM | （推荐）使用控制台凭证作为临时凭证，签署对AWS CLIAWS SDKs、或的编程请求AWS APIs。 |  按照您希望使用的界面的说明进行操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/AmazonElastiCache/latest/dg/set-up.html)  | 
|  人力身份 （在 IAM Identity Center 中管理的用户）  | 使用临时证书签署向AWS CLIAWS SDKs、或发出的编程请求AWS APIs。 |  按照您希望使用的界面的说明进行操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/AmazonElastiCache/latest/dg/set-up.html)  | 
| IAM | 使用临时证书签署向AWS CLIAWS SDKs、或发出的编程请求AWS APIs。 | 按照 IAM 用户指南中的将[临时证书与AWS资源配合使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)中的说明进行操作。 | 
| IAM | （不推荐使用）使用长期凭证签署向AWS CLIAWS SDKs、或发出的编程请求AWS APIs。 |  按照您希望使用的界面的说明进行操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/AmazonElastiCache/latest/dg/set-up.html)  | 

**相关主题:**
+ *IAM 用户指南*中的[什么是 IAM？](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)
+ AWS*AWS一般参考*中的@@ [安全证书](https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)。

## 设置您的权限（仅限新 ElastiCache 用户）
<a name="elasticache-set-up-permissions"></a>

要提供访问权限，请为您的用户、组或角色添加权限：
+ 中的用户和群组AWS IAM Identity Center：

  创建权限集合。按照《AWS IAM Identity Center用户指南》**中[创建权限集](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html)的说明进行操作。
+ 通过身份提供商在 IAM 中托管的用户：

  创建适用于身份联合验证的角色。按照《IAM 用户指南》**中[针对第三方身份提供商创建角色（联合身份验证）](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html)的说明进行操作。
+ IAM 用户：
  + 创建您的用户可以担任的角色。按照《IAM 用户指南》**中[为 IAM 用户创建角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)的说明进行操作。
  + （不推荐使用）将策略直接附加到用户或将用户添加到用户组。按照《IAM 用户指南》**中[向用户添加权限（控制台）](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console)中的说明进行操作。

Amazon ElastiCache 创建并使用服务相关角色代表您配置AWS资源和访问其他资源和服务。 ElastiCache 要为您创建服务相关角色，请使用名为的AWS托管策略。`AmazonElastiCacheFullAccess`此角色预配置了该服务您代表您创建服务相关角色所需的权限。

您可能决定不使用默认策略，而是使用自定义托管策略。在这种情况下，请确保您具有调用 `iam:createServiceLinkedRole` 的权限或创建了 ElastiCache 服务相关角色。

有关更多信息，请参阅下列内容：
+ [创建新策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html)（IAM）
+ [AWS Amazon 的托管政策 ElastiCache](IAM.IdentityBasedPolicies.PredefinedPolicies.md)
+ [将服务相关角色用于 Amazon ElastiCache](using-service-linked-roles.md)

## 设置 EC2
<a name="elasticache-install-configure-ec2"></a>

您将需要设置一个用于连接到缓存的 EC2 实例。
+ 如果您还没有 EC2 实例，请在此处学习如何设置 EC2 实例：[Amazon EC2 入门指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)。
+ 您的 EC2 实例必须位于同一 VPC 中，并且具有与缓存相同的安全组设置。默认情况下，Amazon ElastiCache 会在您的默认 VPC 中创建缓存并使用默认安全组。要学习本教程，请确保您的 EC2 实例位于默认 VPC 中并且具有默认安全组。

## 授予从 Amazon VPC 安全组到您的缓存的网络访问权限
<a name="elasticache-install-grant-access-VPN"></a>

ElastiCache 基于节点的集群使用端口 6379 来执行 Valkey 和 Redis OSS 命令， ElastiCache 无服务器同时使用端口 6379 和端口 6380。为了成功连接并从您的 EC2 实例执行 Valkey 或 Redis OSS 命令，您的安全组必须允许根据需要访问这些端口。

ElastiCache for Memcached 使用 11211 和 11212 端口接受 Memcached 命令。为了成功连接并从您的 EC2 实例执行 Memcached 命令，您的安全组必须允许访问这些端口。

1. 登录AWS Command Line Interface并打开 [Amazon EC2 控制台](https://console.aws.amazon.com/ec2/)。

1. 在导航窗格中的 **Network & Security** 下，选择 **Security Groups**。

1. 从安全组列表中，为 Amazon VPC 选择安全组。除非您创建了供 ElastiCache 使用的安全组，否则该安全组将被命名为 de *fault*。

1. 选择“入站”选项卡，然后：

   1. 选择 **Edit**（编辑）。

   1. 选择**添加规则**。

   1. 在“类型”列中，选择**自定义 TCP 规则**。

   1. 如果使用 Valkey 或 Redis OSS，则在**端口范围**框中键入 `6379`。

      如果使用 Memcached，则在**端口范围**框中键入 `11211`。

   1. 在**源**框中，选择**任何具有端口范围 (0.0.0.0/0) 的任意位置**，这样您在 Amazon VPC 中启动的任何 Amazon EC2 实例都可以连接到您的缓存。

   1. 如果您使用的是 ElastiCache 无服务器，请通过选择添加规则来**添加其他规则**。

   1. 在 **Type** 列中，选择 **Custom TCP rule**。

   1. 如果用 ElastiCache 于 Redis OSS，则在**端口范围**框中键入`6380`。

      如果用 ElastiCache 于 Memcached，则在 “**端口范围**” 框中键入`11212`。

   1. 在**源**框中，选择**任何具有端口范围 (0.0.0.0/0) 的任意位置**，这样您在亚马逊 VPC 中启动的任何 Amazon EC2 实例都可以连接到您的缓存。

   1. 选择**保存**

## 下载并设置命令行访问权限
<a name="Download-and-install-cli"></a>

**下载并安装 *valkey-cli* 实用工具。**

如果你用 ElastiCache 于 Valkey，那么你可能会发现 valkey-cli 实用程序很有用。如果你使用的是带有 redis-cli 的 Redis OSS，可以考虑切换到 valkey-cli，因为它也 ElastiCache 适用于 Redis OSS。

1. 使用您选择的连接实用程序连接到您的 Amazon EC2 实例。有关如何连接亚马逊 EC2 实例的说明，请参阅《[亚马逊 EC2 入门指南》](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)。

1. 根据您的设置运行相应命令，下载并安装 valkey-cli 实用工具。

   **Amazon Linux 2**

   ```
   sudo amazon-linux-extras install epel -y
   sudo yum install gcc jemalloc-devel openssl-devel tcl tcl-devel -y
   wget https://github.com/valkey-io/valkey/archive/refs/tags/8.0.0.tar.gz
   tar xvzf valkey-8.0.0.tar.gz
   cd valkey-8.0.0
   make BUILD_TLS=yes
   ```

**注意**  
当您安装 redis6 程序包时，它会安装 redis6-cli 并默认提供加密支持。
在安装 valkey-cli 或 redis-cli 时，必须为 TLS 提供构建支持。 ElastiCache 只有启用 TLS 后，才能访问无服务器。
如果您要连接到未加密的集群，则不需要 `Build_TLS=yes` 选项。

# 创建 Valkey 无服务器缓存
<a name="GettingStarted.serverless-valkey.step1"></a>

在此步骤中，您将在 Amazon ElastiCache 中创建一个新的缓存。

**AWS 管理控制台**

要使用 ElastiCache 控制台创建新缓存，请执行以下操作：

1. 登录到 AWS 管理控制台 并打开 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)。

1. 在控制台左侧的导航窗格中，选择 **Valkey 缓存**。

1. 在控制台的右侧，选择**创建 Valkey 缓存**。

1. 在**缓存设置**中输入**名称**。您还可以选择为缓存输入**描述**。

1. 保持选中默认设置。

1. 单击**创建**以创建缓存。

1. 缓存处于“活动”状态后，您可以开始在缓存上写入和读取数据。

**AWS CLI**

以下 AWS CLI 示例使用 create-serverless-cache 创建新缓存。

**（Linux**）：

```
aws elasticache create-serverless-cache \
    --serverless-cache-name CacheName \
    --engine valkey
```

**（Windows**）：

```
aws elasticache create-serverless-cache ^
    --serverless-cache-name CacheName ^
    --engine valkey
```

请注意，“状态”字段的值设置为 `CREATING`。

要验证 ElastiCache 是否已完成缓存创建过程，请使用 `describe-serverless-caches` 命令。

**（Linux**）：

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName
```

**（Windows**）：

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName 
```

创建新缓存后，继续执行[对缓存读取和写入数据](GettingStarted.serverless-valkey.step2.md)。

# 对缓存读取和写入数据
<a name="GettingStarted.serverless-valkey.step2"></a>

本节假设您已经创建了一个 Amazon EC2 实例并且可以连接到该实例。有关如何执行此操作的说明，请参阅《[Amazon EC2 入门指南》](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)。

本节还假设您已经为从中连接到缓存的 EC2 实例设置了 VPC 访问权限和安全组设置，并在您的实例上设置了 valkey-cli。 EC2 有关该步骤的更多信息，请参阅[设置 ElastiCache](set-up.md)。

除了以下步骤外，如果您有大型或全局应用程序，可以通过创建和读取副本来显著提升读取性能。有关此高级步骤的更多信息，请参阅[使用只读副本的最佳实践](ReadReplicas.md)。

**查找缓存端点**

**AWS 管理控制台**

要使用 ElastiCache 控制台查找缓存的终端节点，请执行以下操作：

1. 登录AWS 管理控制台并打开 Amazon ElastiCache 控制台，网址为[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)。

1. 在控制台左侧的导航窗格中，选择 **Valkey 缓存**。

1. 在控制台的右侧，单击刚刚创建的缓存的名称。

1. 在**缓存详细信息**中，找到并复制缓存端点。

**AWS CLI**

以下AWS CLI示例说明如何使用 describe-serverless-caches命令查找新缓存的终端节点。运行命令后，查找“端点”字段。

**Linux**

```
aws elasticache describe-serverless-caches \
		--serverless-cache-name CacheName
```

**Windows**

```
aws elasticache describe-serverless-caches ^
		--serverless-cache-name CacheName
```

## 连接到您的 Valkey 缓存（Linux）
<a name="w2aac14c15c37c29b1"></a>

现在您已经有了所需的终端节点，可以登录您的 EC2 实例并连接到缓存。在以下示例中，您使用 *valkey-cli* 实用工具连接到集群。可使用以下命令连接到缓存（注：将 cache-endpoint 替换为您在上一步中检索到的端点）。

```
src/valkey-cli -h cache-endpoint --tls -p 6379
set a "hello"          // Set key "a" with a string value and no expiration
OK
get a                  // Get value for key "a"
"hello"
```

## 连接到您的 Valkey 缓存（Windows）
<a name="w2aac14c15c37c29b3"></a>

现在您已经有了所需的终端节点，可以登录您的 EC2 实例并连接到缓存。在以下示例中，您使用 *valkey-cli* 实用工具连接到集群。可使用以下命令连接到缓存。打开命令提示符，切换到 Valkey 或 Redis 目录并运行命令（注：将 Cache\$1Endpoint 替换为您在上一步中检索到的端点）。

```
c:\Valkey>valkey-cli -h Valkey_Cluster_Endpoint --tls -p 6379
set a "hello"          // Set key "a" with a string value and no expiration
OK
get a                  // Get value for key "a"
"hello"
```

您现在可以继续执行[(可选)清除](GettingStarted.serverless-valkey.step3.md)。

# (可选)清除
<a name="GettingStarted.serverless-valkey.step3"></a>

如果您不再需要已创建的 Amazon ElastiCache 缓存，可以将其删除。此步骤有助于确保不会为未使用的资源付费。您可以使用 ElastiCache 控制台、AWS CLI 或 ElastiCache API 删除缓存。

**AWS 管理控制台**

要使用控制台删除缓存，请执行以下操作：

1. 登录 AWS 管理控制台 并打开 Amazon ElastiCache 控制台（[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)）。

1. 在控制台左侧的导航窗格中，选择 **Valkey 缓存**。

1. 选择要删除的缓存旁边的单选按钮。

1. 选择右上角的**操作**，然后选择**删除**。

1. （可选）您可以选择在删除缓存之前拍摄最终快照。

1. 在**删除**确认屏幕上，重新输入缓存名称并发选择**删除**以删除集群，或选择**取消**以保留集群。

当缓存进入**正在删除**状态之后，您便不再需要支付缓存费用。

**AWS CLI**

以下 AWS CLI 示例使用 delete-serverless-cache 命令删除缓存。

**（Linux**）：

```
aws elasticache delete-serverless-cache \
		--serverless-cache-name CacheName
```

**（Windows**）：

```
aws elasticache delete-serverless-cache ^
		--serverless-cache-name CacheName
```

请注意，**状态**字段的值设置为**正在删除**。

您现在可以继续执行[后续步骤](GettingStarted.serverless-valkey.next-steps.md)。

# 后续步骤
<a name="GettingStarted.serverless-valkey.next-steps"></a>

有关 ElastiCache 的更多信息，请参阅以下页面：
+ [与 ElastiCache](WorkingWithElastiCache.md)
+ [缩放 ElastiCache](Scaling.md)
+ [Amazon ElastiCache 中的日志记录和监控](MonitoringECMetrics.md)
+ [ElastiCache 最佳实践和缓存策略](BestPractices.md)
+ [快照和还原](backups.md)
+ [Amazon SNS 监控 ElastiCache 事件](ECEvents.md)

# 创建 Redis OSS 无服务器缓存
<a name="GettingStarted.serverless-redis.step1"></a>

在此步骤中，您将在 Amazon ElastiCache 中创建一个新的缓存。

**AWS 管理控制台**

要使用 ElastiCache 控制台创建新缓存，请执行以下操作：

1. 登录 AWS 管理控制台 并打开 ElastiCache 控制台（[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)）。

1. 在控制台左侧的导航窗格中，选择 **Redis OSS 缓存**。

1. 在控制台的右侧，选择**创建 Redis OSS 缓存**。

1. 在**缓存设置**中输入**名称**。您还可以选择为缓存输入**描述**。

1. 保持选中默认设置。

1. 单击**创建**以创建缓存。

1. 缓存处于“活动”状态后，您可以开始在缓存上写入和读取数据。

**AWS CLI**

以下 AWS CLI 示例使用 create-serverless-cache 创建新缓存。

**Linux**

```
aws elasticache create-serverless-cache \
    --serverless-cache-name CacheName \
    --engine redis
```

**Windows**

```
aws elasticache create-serverless-cache ^
    --serverless-cache-name CacheName ^
    --engine redis
```

请注意，“状态”字段的值设置为 `CREATING`。

要验证 ElastiCache 是否已完成缓存创建过程，请使用 `describe-serverless-caches` 命令。

**Linux**

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName
```

**Windows**

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName 
```

创建新缓存后，继续执行[对缓存读取和写入数据](GettingStarted.serverless-redis.step2.md)。

# 对缓存读取和写入数据
<a name="GettingStarted.serverless-redis.step2"></a>

本节假设您已经创建了一个 Amazon EC2 实例并且可以连接到该实例。有关如何执行此操作的说明，请参阅《[Amazon EC2 入门指南》](https://aws.amazon.com/ec2/getting-started/)。

本节还假设您已经为从中连接到缓存的 EC2 实例设置了 VPC 访问权限和安全组设置，并在您的实例上设置了 valkey-cli。 EC2 有关该步骤的更多信息，请参阅[设置 ElastiCache](set-up.md)。

**查找缓存端点**

**AWS 管理控制台**

要使用 ElastiCache 控制台查找缓存的终端节点，请执行以下操作：

1. 登录AWS 管理控制台并打开 Amazon ElastiCache 控制台，网址为[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)。

1. 在控制台左侧的导航窗格中，选择 **Valkey 缓存** **Redis OSS 缓存**。

1. 在控制台的右侧，单击刚刚创建的缓存的名称。

1. 在**缓存详细信息**中，找到并复制缓存端点。

**AWS CLI**

以下AWS CLI示例说明如何使用 describe-serverless-caches命令查找新缓存的终端节点。运行命令后，查找“端点”字段。

**Linux**

```
aws elasticache describe-serverless-caches \
		--serverless-cache-name CacheName
```

**Windows**

```
aws elasticache describe-serverless-caches ^
		--serverless-cache-name CacheName
```

## 连接到您的 Valkey 或 Redis OSS 缓存（Linux）
<a name="w2aac14c19c37c27b1"></a>

现在您已经有了所需的终端节点，可以登录您的 EC2 实例并连接到缓存。在以下示例中，您使用 *valkey-cli* 实用工具连接到集群。可使用以下命令连接到缓存（注：将 cache-endpoint 替换为您在上一步中检索到的端点）。

```
src/valkey-cli -h cache-endpoint --tls -p 6379
set a "hello"          // Set key "a" with a string value and no expiration
OK
get a                  // Get value for key "a"
"hello"
```

## 连接到您的 Valkey 或 Redis OSS 缓存（Windows）
<a name="w2aac14c19c37c27b3"></a>

现在您已经有了所需的终端节点，可以登录您的 EC2 实例并连接到缓存。在以下示例中，您使用 *valkey-cli* 实用工具连接到集群。可使用以下命令连接到缓存。打开命令提示符，切换到 Valkey 目录并运行命令（注：将 Cache\$1Endpoint 替换为您在上一步中检索到的端点）。

```
c:\Redis>valkey-cli -h Redis_Cluster_Endpoint --tls -p 6379
set a "hello"          // Set key "a" with a string value and no expiration
OK
get a                  // Get value for key "a"
"hello"
```

您现在可以继续执行[(可选)清除](GettingStarted.serverless-redis.step3.md)。

# (可选)清除
<a name="GettingStarted.serverless-redis.step3"></a>

如果您不再需要已创建的 Amazon ElastiCache 缓存，可以将其删除。此步骤有助于确保不会为未使用的资源付费。您可以使用 ElastiCache 控制台、AWS CLI 或 ElastiCache API 删除缓存。

**AWS 管理控制台**

要使用控制台删除缓存，请执行以下操作：

1. 登录 AWS 管理控制台 并打开 Amazon ElastiCache 控制台（[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)）。

1. 在控制台左侧的导航窗格中，选择 **Valkey 或 Redis OSS 缓存**。

1. 选择要删除的缓存旁边的单选按钮。

1. 选择右上角的**操作**，然后选择**删除**。

1. （可选）您可以选择在删除缓存之前拍摄最终快照。

1. 在**删除**确认屏幕上，重新输入缓存名称并发选择**删除**以删除集群，或选择**取消**以保留集群。

当缓存进入**正在删除**状态之后，您便不再需要支付缓存费用。

**AWS CLI**

以下 AWS CLI 示例使用 delete-serverless-cache 命令删除缓存。

**（Linux**）：

```
aws elasticache delete-serverless-cache \
		--serverless-cache-name CacheName
```

**（Windows**）：

```
aws elasticache delete-serverless-cache ^
		--serverless-cache-name CacheName
```

请注意，**状态**字段的值设置为**正在删除**。

您现在可以继续执行[后续步骤](GettingStarted.serverless-redis.next-steps.md)。

# 后续步骤
<a name="GettingStarted.serverless-redis.next-steps"></a>

有关 ElastiCache 的更多信息，请参阅以下页面：
+ [与 ElastiCache](WorkingWithElastiCache.md)
+ [缩放 ElastiCache](Scaling.md)
+ [Amazon ElastiCache 中的日志记录和监控](MonitoringECMetrics.md)
+ [ElastiCache 最佳实践和缓存策略](BestPractices.md)
+ [快照和还原](backups.md)
+ [Amazon SNS 监控 ElastiCache 事件](ECEvents.md)

# 创建 Memcached 无服务器缓存
<a name="create-serverless-cache-mem"></a>

**AWS 管理控制台**

要使用 ElastiCache 控制台创建新的 Memcached 无服务器缓存，请执行以下操作：

1. 登录 AWS 管理控制台 并打开 ElastiCache 控制台（[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)）。

1. 在控制台左侧的导航窗格中，选择 **Memcached 缓存**。

1. 在控制台的右侧，选择**创建 Memcached 缓存**。

1. 在**缓存设置**中输入**名称**。您还可以选择为缓存输入**描述**。

1. 保持选中默认设置。

1. 单击**创建**以创建缓存。

1. 缓存处于“活动”状态后，您可以开始在缓存上写入和读取数据。

使用 AWS CLI 创建新的缓存

以下 AWS CLI 示例使用 create-serverless-cache 创建新缓存。

**（Linux**）：

```
aws elasticache create-serverless-cache \
		--serverless-cache-name CacheName \
		--engine memcached
```

**（Windows**）：

```
aws elasticache create-serverless-cache ^
		--serverless-cache-name CacheName ^
		--engine memcached
```

请注意，“状态”字段的值设置为 `CREATING`。

要验证 ElastiCache 是否已完成缓存创建过程，请使用 `describe-serverless-caches` 命令。

**（Linux**）：

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName
```

**（Windows**）：

```
aws elasticache describe-serverless-caches --serverless-cache-name CacheName
```

创建新缓存后，继续执行[对缓存读取和写入数据](read-write-cache-mem.md)。

# 对缓存读取和写入数据
<a name="read-write-cache-mem"></a>

本节假设您已经创建了一个 Amazon EC2 实例并且可以连接到该实例。有关如何执行此操作的说明，请参阅《[Amazon EC2 入门指南》](https://aws.amazon.com/ec2/getting-started/)。

默认情况下，在您的默认 VPC 中 ElastiCache 创建缓存。确保您的 EC2 实例也是在默认 VPC 中创建的，以便它能够连接到缓存。

**查找缓存端点**

**AWS 管理控制台**

要使用 ElastiCache 控制台查找缓存的终端节点，请执行以下操作：

1. 登录AWS 管理控制台并打开 Amazon ElastiCache 控制台，网址为[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)。

1. 在控制台左侧的导航窗格中，选择 **Memcached 缓存**。

1. 在控制台的右侧，单击刚刚创建的缓存的名称。

1. 在**缓存详细信息**中，找到并复制缓存端点。

**AWS CLI**

以下AWS CLI示例说明如何使用 describe-serverless-caches命令查找新缓存的终端节点。运行命令后，查找“端点”字段。

**Linux**

```
aws elasticache describe-serverless-caches \
		--serverless-cache-name CacheName
```

**Windows**

```
aws elasticache describe-serverless-caches ^
		--serverless-cache-name CacheName
```

## 使用 OpenSSL 进行连接
<a name="w2aac14c21c41c29b1"></a>

 有关如何使用 OpenSSL 进行连接的信息，请参阅 [ElastiCache 传输中加密 (TLS)](in-transit-encryption.md)

## 使用 Memcached Java 客户端进行连接
<a name="w2aac14c21c41c29b3"></a>

```
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.FailureMode;
import net.spy.memcached.MemcachedClient;

public class TLSDemo {
    public static void main(String[] args) throws Exception {
        ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
        // Build SSLContext
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        // Create the client in TLS mode
        connectionFactoryBuilder.setSSLContext(sslContext);
        // Set Failure Mode to Retry
        connectionFactoryBuilder.setFailureMode(FailureMode.Retry);
        MemcachedClient client = new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses("mycluster-fnjyzo.serverless.use1.cache.amazonaws.com:11211"));

        // Store a data item for an hour.
        client.set("theKey", 3600, "This is the data value");
    }
}
```

## 使用 Memcached PHP 客户端进行连接
<a name="w2aac14c21c41c29b5"></a>

```
<?php
$cluster_endpoint = "mycluster.serverless.use1.cache.amazonaws.com";
$server_port = 11211; 

/* Initialize a persistent Memcached client in TLS mode */
$tls_client = new Memcached('persistent-id');
$tls_client->addServer($cluster_endpoint, $server_port);
if(!$tls_client->setOption(Memcached::OPT_USE_TLS, 1)) {
    echo $tls_client->getLastErrorMessage(), "\n";
    exit(1);
}
$tls_config = new MemcachedTLSContextConfig();
$tls_config->hostname = '*.serverless.use1.cache.amazonaws.com';
$tls_config->skip_cert_verify = false;
$tls_config->skip_hostname_verify = false;
$tls_client->createAndSetTLSContext((array)$tls_config); 

 /* store the data for 60 seconds in the cluster */
$tls_client->set('key', 'value', 60);
?>
```

## 使用 Memcached Python 客户端（Pymemcache）进行连接
<a name="w2aac14c21c41c29b7"></a>

请参阅 [https://pymemcache.readthedocs。 io/en/latest/getting](https://pymemcache.readthedocs.io/en/latest/getting_started.html)\$1started.html

```
import ssl
from pymemcache.client.base import Client
		
context = ssl.create_default_context()
cluster_endpoint = <To be taken from the AWS CLI / console>
target_port = 11211
memcached_client = Client(("{cluster_endpoint}", target_port), tls_context=context)
memcached_client.set("key", "value", expire=500, noreply=False)
assert self.memcached_client.get("key").decode() == "value"
```

## 使用 Memcached NodeJS/TS 客户端（Electrode-IO 内存缓存）连接
<a name="w2aac14c21c41c29b9"></a>

[参见[https://github.com/electrode-io/内存缓存和内存缓存](https://github.com/electrode-io/memcache)客户端 https://www.npmjs.com/package/](https://www.npmjs.com/package/memcache-client)

通过 `npm i memcache-client` 进行安装

在应用程序中，按以下所示创建 memcached TLS 客户端：

```
var memcache = require("memcache-client");
const client = new memcache.MemcacheClient({server: "{cluster_endpoint}:11211", tls: {}});
client.set("key", "value");
```

## 使用 Memcached Rust 客户端（rust-memcache）进行连接
<a name="w2aac14c21c41c29c11"></a>

见 [https://crates。 io/crates/memcache](https://crates.io/crates/memcache)还有 [https://github.com/aisk/rust-memcach](https://github.com/aisk/rust-memcache) e。

```
// create connection with to memcached server node:
let client = memcache::connect("memcache+tls://<cluster_endpoint>:11211?verify_mode=none").unwrap();
				
// set a string value
client.set("foo", "bar", 0).unwrap();
```

## 使用 Memcached Go 客户端（Gomemcache）进行连接
<a name="w2aac14c21c41c29c13"></a>

见 [https://github.com/bradfitz/gomemcach](https://github.com/bradfitz/gomemcache) e

```
c := New(net.JoinHostPort("{cluster_endpoint}", strconv.Itoa(port)))
c.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var td tls.Dialer
td.Config = &tls.Config{}
return td.DialContext(ctx, network, addr)
}
foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123}
err := c.Set(foo)
```

## 使用 Memcached Ruby 客户端（Dalli）进行连接
<a name="w2aac14c21c41c29c15"></a>

见 [https://github.com/petergoldstein/dalli](https://github.com/petergoldstein/dalli)

```
require 'dalli'
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.ssl_version = :SSLv23
ssl_context.verify_hostname = true
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER
client = Dalli::Client.new("<cluster_endpoint>:11211", :ssl_context => ssl_context); 
client.get("abc")
```

## 使用 Memcached .NET 客户端连接 () EnyimMemcachedCore
<a name="w2aac14c21c41c29c17"></a>

请参阅 [https://github.com/cnblogs/EnyimMemcachedCore](https://github.com/cnblogs/EnyimMemcachedCore)。

```
"MemcachedClient": {
"Servers": [
{
"Address": "{cluster_endpoint}",
"Port": 11211
}
],
"UseSslStream":  true
}
```

您现在可以继续执行[（可选）清理](read-write-cleanup-mem.md)。

# （可选）清理
<a name="read-write-cleanup-mem"></a>

**使用AWS 管理控制台**

以下过程从您的部署中删除单个缓存。要删除多个缓存，请对要删除的每个缓存重复此过程。您无需等待删除一个缓存的过程完成，即可开始删除另一个缓存。

**删除缓存**

1. 登录AWS 管理控制台并打开 Amazon ElastiCache 控制台，网址为[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)。

1. 在 ElastiCache 控制台仪表板中，选择要删除的缓存上运行的引擎。此时会显示运行该引擎的所有缓存的列表。

1. 要选择缓存以便删除，请从缓存列表中选择缓存的名称。
**重要**  
 您一次只能从 ElastiCache 控制台删除一个缓存。选择多个缓存会禁用删除操作。

1. 对于**操作**，选择**删除**。

1. 在**删除缓存**确认屏幕上，选择**删除**可删除缓存，选择**取消**可保留集群。

1. 如果选择了**删除**，则缓存的状态将变为*正在删除*。

当缓存进入**正在删除**状态之后，您便不再需要支付缓存费用。

**使用AWS CLI**

下面的代码删除缓存 my-cache。

```
aws elasticache delete-serverless-cache --serverless-cache-name my-cache
```

C delete-serverless-cache LI 操作仅删除一个无服务器缓存。要删除多个缓存，请调 delete-serverless-cache用要删除的每个无服务器缓存。您无需等待删除一个无服务器缓存的过程完成，即可开始删除另一个。

**对于 Linux、macOS 或 Unix**：

```
aws elasticache delete-serverless-cache \
		--serverless-cache-name my-cache
```

**对于 Windows：**

```
aws elasticache delete-serverless-cache ^
		--serverless-cache-name my-cache
```

有关更多信息，请参阅 f AWS CLI or ElastiCache 主题 delete-serverless-cache。

您现在可以继续执行[后续步骤](next-steps-mem.md)。

# 后续步骤
<a name="next-steps-mem"></a>

有关 ElastiCache 的更多信息，请参阅：
+ [与 ElastiCache](WorkingWithElastiCache.md)
+ [缩放 ElastiCache](Scaling.md)
+ [ElastiCache 的配额](quota-limits.md)
+ [ElastiCache 最佳实践和缓存策略](BestPractices.md)
+ [查看 ElastiCache 事件](ECEvents.Viewing.md)

# 教程：Python 和 ElastiCache 入门
<a name="ElastiCache-Getting-Started-Tutorials"></a>

本部分包含动手实践教程，旨在帮助您了解 ElastiCache for Valkey 和 ElastiCache for Redis OSS。我们鼓励您通读一份特定于语言的教程。

**注意**  
AWS SDK 适用于各种语言。有关完整列表，请参阅[用于 Amazon Web Services 的工具](https://aws.amazon.com/tools/)。

**Topics**
+ [Python 和 ElastiCache](ElastiCache-Getting-Started-Tutorials-Python.md)

# Python 和 ElastiCache
<a name="ElastiCache-Getting-Started-Tutorials-Python"></a>

在本教程中，您将使用适用于 Python 的AWS SDK (Boto3) 来编写用于执行以下操作的简单程序： ElastiCache 
+  ElastiCache 为 Redis OSS 集群创建（启用集群模式和禁用集群模式）
+ 检查用户或用户组是否存在，如不存在，请进行创建。（此功能适用于 Valkey 7.2 和更高版本，以及 Redis OSS 6.0 到 7.1。）
+ 连接到 ElastiCache
+ 执行诸如设置和获取字符串、从 Steam 中读取和写入以及从频道发布和订阅等操作。 Pub/Sub 

在学习本教程时，你可以参考适用于 Python 的AWS软件开发工具包 (Boto) 文档。以下部分特定于 ElastiCache：[ElastiCache 低级客户端](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elasticache.html)

## 教程的先决条件
<a name="ElastiCache-Getting-Started-Tutorials-Prerquisites"></a>
+ 设置AWS访问密钥以使用AWS SDKs。有关更多信息，请参阅 [设置 ElastiCache](set-up.md)。
+ 安装 Python 3.0 或更高版本。欲了解更多信息，请参阅 [https://www.python.org/downloads](https://www.python.org/downloads)。有关说明，请参阅 Boto 3 文档中的[快速入门](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)。

**Topics**
+ [教程的先决条件](#ElastiCache-Getting-Started-Tutorials-Prerquisites)
+ [教程：创建 ElastiCache 集群和用户](#ElastiCache-Getting-Started-Tutorials-Create-Cluster-and-Users)
+ [教程：连接到 ElastiCache](#ElastiCache-Getting-Started-Tutorials-Connecting)
+ [用法示例](#ElastiCache-Getting-Started-Tutorials-Usage)

## 教程：创建 ElastiCache 集群和用户
<a name="ElastiCache-Getting-Started-Tutorials-Create-Cluster-and-Users"></a>

以下示例使用 boto3 开发工具包进行 Redis OSS 管理操作（创建集群或用户），使用 redis redis-py-cluster -py/ 进行数据处理。 ElastiCache 

**Topics**
+ [创建已禁用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-Create-Cluster)
+ [创建采用 TLS 和 RBAC 且已禁用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-RBAC)
+ [创建已启用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-Cluster-Enabled)
+ [创建采用 TLS 和 RBAC 且已启用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-Cluster-RBAC)
+ [检查是否 users/usergroup 存在，否则请创建它们](#ElastiCache-Getting-Started-Tutorials-Users)

### 创建已禁用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-Create-Cluster"></a>

复制以下程序并将其粘贴到名为 *CreateClusterModeDisabledCluster.py* 的文件中。

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_disabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumCacheClusters=2,ReplicationGroupDescription='Sample cluster',ReplicationGroupId=None):
    """Creates an ElastiCache Cluster with cluster mode disabled

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumCacheClusters: Number of nodes in the cluster. Minimum 1 (just a primary node) and maximun 6 (1 primary and 5 replicas).
    If not specified, cluster will be created with 1 primary and 1 replica.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'

    response = client.create_replication_group(
        AutomaticFailoverEnabled=True,
        CacheNodeType=CacheNodeType,
        Engine='valkey',
        EngineVersion=EngineVersion,
        NumCacheClusters=NumCacheClusters,
        ReplicationGroupDescription=ReplicationGroupDescription,
        ReplicationGroupId=ReplicationGroupId,
        SnapshotRetentionLimit=30,
    )
    return response


if __name__ == '__main__':
    
    # Creates an ElastiCache Cluster mode disabled cluster, based on cache.m6g.large nodes, Valkey 8.0, one primary and two replicas
    elasticacheResponse = create_cluster_mode_disabled(
        #CacheNodeType='cache.m6g.large', 
        EngineVersion='8.0',
        NumCacheClusters=3,
        ReplicationGroupDescription='Valkey cluster mode disabled with replicas',
        ReplicationGroupId='valkey202104053'
        )
    
    logging.info(elasticacheResponse)
```

要运行该程序，请输入以下命令：

 `python CreateClusterModeDisabledCluster.py`

有关更多信息，请参阅 [在 ElastiCache 中管理集群](Clusters.md)。

### 创建采用 TLS 和 RBAC 且已禁用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-RBAC"></a>

为确保安全性，在创建已禁用集群模式的集群时，您可以使用传输层安全性 (TLS) 和基于角色的访问控制 (RBAC)。与 Valkey 或 Redis OSS AUTH（如果对客户端令牌进行身份验证，则所有经过身份验证的客户端都对复制组具有完全的访问权限）不同的是，RBAC 让您能够通过用户组控制集群访问权限。这些用户组旨在作为一种管理对复制组的访问权限的方式。有关更多信息，请参阅 [基于角色的访问控制（RBAC）](Clusters.RBAC.md)。

复制以下程序并将其粘贴到名为 *ClusterModeDisabledWithRBAC.py* 的文件中。

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_disabled_rbac(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumCacheClusters=2,ReplicationGroupDescription='Sample cluster',ReplicationGroupId=None, UserGroupIds=None, SecurityGroupIds=None,CacheSubnetGroupName=None):
    """Creates an ElastiCache Cluster with cluster mode disabled and RBAC

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumCacheClusters: Number of nodes in the cluster. Minimum 1 (just a primary node) and maximun 6 (1 primary and 5 replicas).
    If not specified, cluster will be created with 1 primary and 1 replica.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Mandatory name for the cluster.
    :param UserGroupIds: The ID of the user group to be assigned to the cluster.
    :param SecurityGroupIds: List of security groups to be assigned. If not defined, default will be used
    :param CacheSubnetGroupName: subnet group where the cluster will be placed. If not defined, default will be used.
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return {'Error': 'ReplicationGroupId parameter is required'}
    elif not isinstance(UserGroupIds,(list)):
        return {'Error': 'UserGroupIds parameter is required and must be a list'}

    params={'AutomaticFailoverEnabled': True, 
            'CacheNodeType': CacheNodeType, 
            'Engine': 'valkey', 
            'EngineVersion': EngineVersion, 
            'NumCacheClusters': NumCacheClusters, 
            'ReplicationGroupDescription': ReplicationGroupDescription, 
            'ReplicationGroupId': ReplicationGroupId, 
            'SnapshotRetentionLimit': 30, 
            'TransitEncryptionEnabled': True, 
            'UserGroupIds':UserGroupIds
        }

    # defaults will be used if CacheSubnetGroupName or SecurityGroups are not explicit.
    if isinstance(SecurityGroupIds,(list)):
        params.update({'SecurityGroupIds':SecurityGroupIds})
    if CacheSubnetGroupName:
        params.update({'CacheSubnetGroupName':CacheSubnetGroupName})

    response = client.create_replication_group(**params)
    return response

if __name__ == '__main__':

    # Creates an ElastiCache Cluster mode disabled cluster, based on cache.m6g.large nodes, Valkey 8.0, one primary and two replicas.
    # Assigns the existent user group "mygroup" for RBAC authentication
   
    response=create_cluster_mode_disabled_rbac(
        CacheNodeType='cache.m6g.large',
        EngineVersion='8.0',
        NumCacheClusters=3,
        ReplicationGroupDescription='Valkey cluster mode disabled with replicas',
        ReplicationGroupId='valkey202104',
        UserGroupIds=[
            'mygroup'
        ],
        SecurityGroupIds=[
            'sg-7cc73803'
        ],
        CacheSubnetGroupName='default'
    )

    logging.info(response)
```

要运行该程序，请输入以下命令：

 `python ClusterModeDisabledWithRBAC.py`

有关更多信息，请参阅 [在 ElastiCache 中管理集群](Clusters.md)。

### 创建已启用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-Cluster-Enabled"></a>

复制以下程序并将其粘贴到名为 *ClusterModeEnabled.py* 的文件中。

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_enabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumNodeGroups=1,ReplicasPerNodeGroup=1, ReplicationGroupDescription='Sample cache with cluster mode enabled',ReplicationGroupId=None):
    """Creates an ElastiCache Cluster with cluster mode enabled

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumNodeGroups: Number of shards in the cluster. Minimum 1 and maximun 90.
    If not specified, cluster will be created with 1 shard.
    :param ReplicasPerNodeGroup: Number of replicas per shard. If not specified 1 replica per shard will be created.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'
    
    response = client.create_replication_group(
        AutomaticFailoverEnabled=True,
        CacheNodeType=CacheNodeType,
        Engine='valkey',
        EngineVersion=EngineVersion,
        ReplicationGroupDescription=ReplicationGroupDescription,
        ReplicationGroupId=ReplicationGroupId,
    #   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary node (implicit) and 2 replicas (replicasPerNodeGroup)
        NumNodeGroups=NumNodeGroups,
        ReplicasPerNodeGroup=ReplicasPerNodeGroup,
        CacheParameterGroupName='default.valkey7.2.cluster.on'
    )

    return response


# Creates a cluster mode enabled 
response = create_cluster_mode_enabled(
    CacheNodeType='cache.m6g.large',
    EngineVersion='6.0',
    ReplicationGroupDescription='Valkey cluster mode enabled with replicas',
    ReplicationGroupId='valkey20210',
#   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary (implicit) and 2 replicas (replicasPerNodeGroup)
    NumNodeGroups=2,
    ReplicasPerNodeGroup=1,
)

logging.info(response)
```

要运行该程序，请输入以下命令：

 `python ClusterModeEnabled.py`

有关更多信息，请参阅 [在 ElastiCache 中管理集群](Clusters.md)。

### 创建采用 TLS 和 RBAC 且已启用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-Cluster-RBAC"></a>

为确保安全性，在创建已启用集群模式的集群时，您可以使用传输层安全性 (TLS) 和基于角色的访问控制 (RBAC)。与 Valkey 或 Redis OSS AUTH（如果对客户端令牌进行身份验证，则所有经过身份验证的客户端都对复制组具有完全的访问权限）不同的是，RBAC 让您能够通过用户组控制集群访问权限。这些用户组旨在作为一种管理对复制组的访问权限的方式。有关更多信息，请参阅 [基于角色的访问控制（RBAC）](Clusters.RBAC.md)。

复制以下程序并将其粘贴到名为 *ClusterModeEnabledWithRBAC.py* 的文件中。

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_enabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumNodeGroups=1,ReplicasPerNodeGroup=1, ReplicationGroupDescription='Sample cache with cluster mode enabled',ReplicationGroupId=None,UserGroupIds=None, SecurityGroupIds=None,CacheSubnetGroupName=None,CacheParameterGroupName='default.valkey7.2.cluster.on'):
    """Creates an ElastiCache Cluster with cluster mode enabled and RBAC

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumNodeGroups: Number of shards in the cluster. Minimum 1 and maximun 90.
    If not specified, cluster will be created with 1 shard.
    :param ReplicasPerNodeGroup: Number of replicas per shard. If not specified 1 replica per shard will be created.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster.
    :param CacheParameterGroupName: Parameter group to be used. Must be compatible with the engine version and cluster mode enabled.
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'
    elif not isinstance(UserGroupIds,(list)):
        return {'Error': 'UserGroupIds parameter is required and must be a list'}

    params={'AutomaticFailoverEnabled': True, 
            'CacheNodeType': CacheNodeType, 
            'Engine': 'valkey', 
            'EngineVersion': EngineVersion, 
            'ReplicationGroupDescription': ReplicationGroupDescription, 
            'ReplicationGroupId': ReplicationGroupId, 
            'SnapshotRetentionLimit': 30, 
            'TransitEncryptionEnabled': True, 
            'UserGroupIds':UserGroupIds,
            'NumNodeGroups': NumNodeGroups,
            'ReplicasPerNodeGroup': ReplicasPerNodeGroup,
            'CacheParameterGroupName': CacheParameterGroupName
        }

    # defaults will be used if CacheSubnetGroupName or SecurityGroups are not explicit.
    if isinstance(SecurityGroupIds,(list)):
        params.update({'SecurityGroupIds':SecurityGroupIds})
    if CacheSubnetGroupName:
        params.update({'CacheSubnetGroupName':CacheSubnetGroupName})

    response = client.create_replication_group(**params)
    return response

if __name__ == '__main__':
    # Creates a cluster mode enabled cluster
    response = create_cluster_mode_enabled(
        CacheNodeType='cache.m6g.large',
        EngineVersion='7.2',
        ReplicationGroupDescription='Valkey cluster mode enabled with replicas',
        ReplicationGroupId='valkey2021',
    #   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary (implicit) and 2 replicas (replicasPerNodeGroup)
        NumNodeGroups=2,
        ReplicasPerNodeGroup=1,
        UserGroupIds=[
            'mygroup'
        ],
        SecurityGroupIds=[
            'sg-7cc73803'
        ],
        CacheSubnetGroupName='default'

    )
    
    logging.info(response)
```

要运行该程序，请输入以下命令：

 `python ClusterModeEnabledWithRBAC.py`

有关更多信息，请参阅 [在 ElastiCache 中管理集群](Clusters.md)。

### 检查是否 users/usergroup 存在，否则请创建它们
<a name="ElastiCache-Getting-Started-Tutorials-Users"></a>

通过 RBAC，您可以使用访问字符串创建用户并为其分配特定权限。您可以将用户分配到与特定角色（管理员、人力资源）对应的用户组，然后将这些用户组部署到一个或多 ElastiCache 个 Redis OSS 复制组中。这样，您可以在使用相同 Valkey 或 Redis OSS 复制组的客户端之间建立安全边界，并阻止客户端彼此访问数据。有关更多信息，请参阅 [基于角色的访问控制（RBAC）](Clusters.RBAC.md)。

复制以下程序并将其粘贴到名为 *UserAndUserGroups.py* 的文件中。更新用于提供凭证的机制。此示例中的凭证显示为可替换凭证，并分配了未声明的项目。避免对凭证进行硬编码。

此示例使用了包含用户权限的访问字符串。有关访问字符串的更多信息，请参阅[使用访问字符串指定权限](Clusters.RBAC.md#Access-string)。

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def check_user_exists(UserId):
    """Checks if UserId exists

    Returns True if UserId exists, otherwise False
    :param UserId: ElastiCache User ID
    :return: True|False
    """
    try:
        response = client.describe_users(
            UserId=UserId,
        )
        if response['Users'][0]['UserId'].lower() == UserId.lower():
            return True
    except Exception as e:
        if e.response['Error']['Code'] == 'UserNotFound':
            logging.info(e.response['Error'])
            return False
        else:
            raise

def check_group_exists(UserGroupId):
    """Checks if UserGroupID exists

    Returns True if Group ID exists, otherwise False
    :param UserGroupId: ElastiCache User ID
    :return: True|False
    """

    try:
        response = client.describe_user_groups(
            UserGroupId=UserGroupId
        )
        if response['UserGroups'][0]['UserGroupId'].lower() == UserGroupId.lower():
            return True
    except Exception as e:
        if e.response['Error']['Code'] == 'UserGroupNotFound':
            logging.info(e.response['Error'])
            return False
        else:
            raise

def create_user(UserId=None,UserName=None,Password=None,AccessString=None):
    """Creates a new user

    Returns the ARN for the newly created user or the error message
    :param UserId: ElastiCache user ID. User IDs must be unique
    :param UserName: ElastiCache user name. ElastiCache allows multiple users with the same name as long as the associated user ID is unique.
    :param Password: Password for user. Must have at least 16 chars.
    :param AccessString: Access string with the permissions for the user. 
    :return: user ARN
    """
    try:
        response = client.create_user(
            UserId=UserId,
            UserName=UserName,
            Engine='Redis',
            Passwords=[Password],
            AccessString=AccessString,
            NoPasswordRequired=False
        )
        return response['ARN']
    except Exception as e:
        logging.info(e.response['Error'])
        return e.response['Error']

def create_group(UserGroupId=None, UserIds=None):
    """Creates a new group.
    A default user is required (mandatory) and should be specified in the UserIds list

    Return: Group ARN
    :param UserIds: List with user IDs to be associated with the new group. A default user is required
    :param UserGroupId: The ID (name) for the group
    :return: Group ARN
    """
    try:
        response = client.create_user_group(
            UserGroupId=UserGroupId,
            Engine='Redis',
            UserIds=UserIds
        )
        return response['ARN']
    except Exception as e:
        logging.info(e.response['Error'])


if __name__ == '__main__':
    
    groupName='mygroup2'
    userName = 'myuser2'
    userId=groupName+'-'+userName

    # Creates a new user if the user ID does not exist.
    for tmpUserId,tmpUserName in [ (userId,userName), (groupName+'-default','default')]:
        if not check_user_exists(tmpUserId):
            response=create_user(UserId=tmpUserId, UserName=EXAMPLE,Password=EXAMPLE,AccessString='on ~* +@all')
            logging.info(response)
        # assigns the new user ID to the user group
    if not check_group_exists(groupName):
        UserIds = [ userId , groupName+'-default']
        response=create_group(UserGroupId=groupName,UserIds=UserIds)
        logging.info(response)
```

要运行该程序，请输入以下命令：

 `python UserAndUserGroups.py`

## 教程：连接到 ElastiCache
<a name="ElastiCache-Getting-Started-Tutorials-Connecting"></a>

以下示例使用 Valkey 或 Redis OSS 客户端进行连接。 ElastiCache

**Topics**
+ [连接到已禁用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-disabled)
+ [连接到已启用集群模式的集群](#ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-enabled)

### 连接到已禁用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-disabled"></a>

复制以下程序并将其粘贴到名为 *ConnectClusterModeDisabled.py* 的文件中。更新用于提供凭证的机制。此示例中的凭证显示为可替换凭证，并分配了未声明的项目。避免对凭证进行硬编码。

```
from redis import Redis
import logging

logging.basicConfig(level=logging.INFO)
redis = Redis(host='primary.xxx.yyyyyy.zzz1.cache.amazonaws.com', port=6379, decode_responses=True, ssl=True, username=example, password=EXAMPLE)

if redis.ping():
    logging.info("Connected to Redis")
```

要运行该程序，请输入以下命令：

 `python ConnectClusterModeDisabled.py`

### 连接到已启用集群模式的集群
<a name="ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-enabled"></a>

复制以下程序并将其粘贴到名为 *ConnectClusterModeEnabled.py* 的文件中。

```
from rediscluster import RedisCluster
import logging

logging.basicConfig(level=logging.INFO)
redis = RedisCluster(startup_nodes=[{"host": "xxx.yyy.clustercfg.zzz1.cache.amazonaws.com","port": "6379"}], decode_responses=True,skip_full_coverage_check=True)

if redis.ping():
    logging.info("Connected to Redis")
```

要运行该程序，请输入以下命令：

 `python ConnectClusterModeEnabled.py`

## 用法示例
<a name="ElastiCache-Getting-Started-Tutorials-Usage"></a>

以下示例使用适用于 Redis OSS 的 ElastiCache boto3 开发工具包。 ElastiCache 

**Topics**
+ [设置和获取字符串](#ElastiCache-Getting-Started-Tutorials-set-strings)
+ [设置和获取包含多个项目的哈希](#ElastiCache-Getting-Started-Tutorials-set-hash)
+ [从 Pub/Sub 频道发布（写入）和订阅（读取）](#ElastiCache-Getting-Started-Tutorials-pub-sub)
+ [从流中写入和读取](#ElastiCache-Getting-Started-Tutorials-read-write-stream)

### 设置和获取字符串
<a name="ElastiCache-Getting-Started-Tutorials-set-strings"></a>

复制以下程序并将其粘贴到名为 *SetAndGetStrings.py* 的文件中。

```
import time
import logging
logging.basicConfig(level=logging.INFO,format='%(asctime)s: %(message)s')

keyName='mykey'
currTime=time.ctime(time.time())

# Set the key 'mykey' with the current date and time as value. 
# The Key will expire and removed from cache in 60 seconds.
redis.set(keyName, currTime, ex=60)

# Sleep just for better illustration of TTL (expiration) value
time.sleep(5)

# Retrieve the key value and current TTL
keyValue=redis.get(keyName)
keyTTL=redis.ttl(keyName)

logging.info("Key {} was set at {} and has {} seconds until expired".format(keyName, keyValue, keyTTL))
```

要运行该程序，请输入以下命令：

 `python SetAndGetStrings.py`

### 设置和获取包含多个项目的哈希
<a name="ElastiCache-Getting-Started-Tutorials-set-hash"></a>

复制以下程序并将其粘贴到名为 *SetAndGetHash.py* 的文件中。

```
import logging
import time

logging.basicConfig(level=logging.INFO,format='%(asctime)s: %(message)s')

keyName='mykey'
keyValues={'datetime': time.ctime(time.time()), 'epochtime': time.time()}

# Set the hash 'mykey' with the current date and time in human readable format (datetime field) and epoch number (epochtime field). 
redis.hset(keyName, mapping=keyValues)

# Set the key to expire and removed from cache in 60 seconds.
redis.expire(keyName, 60)

# Sleep just for better illustration of TTL (expiration) value
time.sleep(5)

# Retrieves all the fields and current TTL
keyValues=redis.hgetall(keyName)
keyTTL=redis.ttl(keyName)

logging.info("Key {} was set at {} and has {} seconds until expired".format(keyName, keyValues, keyTTL))
```

要运行该程序，请输入以下命令：

 `python SetAndGetHash.py`

### 从 Pub/Sub 频道发布（写入）和订阅（读取）
<a name="ElastiCache-Getting-Started-Tutorials-pub-sub"></a>

复制以下程序并将其粘贴到名为 *PubAndSub.py* 的文件中。

```
import logging
import time

def handlerFunction(message):
    """Prints message got from PubSub channel to the log output

    Return None
    :param message: message to log
    """
    logging.info(message)

logging.basicConfig(level=logging.INFO)
redis = Redis(host="redis202104053.tihewd.ng.0001.use1.cache.amazonaws.com", port=6379, decode_responses=True)


# Creates the subscriber connection on "mychannel"
subscriber = redis.pubsub()
subscriber.subscribe(**{'mychannel': handlerFunction})

# Creates a new thread to watch for messages while the main process continues with its routines
thread = subscriber.run_in_thread(sleep_time=0.01)

# Creates publisher connection on "mychannel"
redis.publish('mychannel', 'My message')

# Publishes several messages. Subscriber thread will read and print on log.
while True:
    redis.publish('mychannel',time.ctime(time.time()))
    time.sleep(1)
```

要运行该程序，请输入以下命令：

 `python PubAndSub.py`

### 从流中写入和读取
<a name="ElastiCache-Getting-Started-Tutorials-read-write-stream"></a>

复制以下程序并将其粘贴到名为 *ReadWriteStream.py* 的文件中。

```
from redis import Redis
import redis.exceptions as exceptions
import logging
import time
import threading

logging.basicConfig(level=logging.INFO)

def writeMessage(streamName):
    """Starts a loop writting the current time and thread name to 'streamName'

    :param streamName: Stream (key) name to write messages.
    """
    fieldsDict={'writerId':threading.currentThread().getName(),'myvalue':None}
    while True:
        fieldsDict['myvalue'] = time.ctime(time.time())
        redis.xadd(streamName,fieldsDict)
        time.sleep(1)

def readMessage(groupName=None,streamName=None):
    """Starts a loop reading from 'streamName'
    Multiple threads will read from the same stream consumer group. Consumer group is used to coordinate data distribution.
    Once a thread acknowleges the message, it won't be provided again. If message wasn't acknowledged, it can be served to another thread.

    :param groupName: stream group were multiple threads will read.
    :param streamName: Stream (key) name where messages will be read.
    """

    readerID=threading.currentThread().getName()
    while True:
        try:
            # Check if the stream has any message
            if redis.xlen(streamName)>0:
                # Check if if the messages are new (not acknowledged) or not (already processed)
                streamData=redis.xreadgroup(groupName,readerID,{streamName:'>'},count=1)
                if len(streamData) > 0:
                    msgId,message = streamData[0][1][0]
                    logging.info("{}: Got {} from ID {}".format(readerID,message,msgId))
                    #Do some processing here. If the message has been processed sucessfuly, acknowledge it and (optional) delete the message.
                    redis.xack(streamName,groupName,msgId)
                    logging.info("Stream message ID {} read and processed successfuly by {}".format(msgId,readerID))
                    redis.xdel(streamName,msgId)
            else:
                pass
        except:
            raise
            
        time.sleep(0.5)

# Creates the stream 'mystream' and consumer group 'myworkergroup' where multiple threads will write/read.
try:
    redis.xgroup_create('mystream','myworkergroup',mkstream=True)
except exceptions.ResponseError as e:
    logging.info("Consumer group already exists. Will continue despite the error: {}".format(e))
except:
    raise

# Starts 5 writer threads.
for writer_no in range(5):
    writerThread = threading.Thread(target=writeMessage, name='writer-'+str(writer_no), args=('mystream',),daemon=True)
    writerThread.start()

# Starts 10 reader threads
for reader_no in range(10):
    readerThread = threading.Thread(target=readMessage, name='reader-'+str(reader_no), args=('myworkergroup','mystream',),daemon=True)
    readerThread.daemon = True
    readerThread.start()

# Keep the code running for 30 seconds
time.sleep(30)
```

要运行该程序，请输入以下命令：

 `python ReadWriteStream.py`

# 教程：将 Lambda 配置为在 VPC ElastiCache 中进行访问
<a name="LambdaRedis"></a>

在本教程中，您可以学习如何创建 ElastiCache 无服务器缓存，创建 Lambda 函数，然后测试 Lambda 函数，然后选择在之后进行清理。

**Topics**
+ [步骤 1：创建 ElastiCache 无服务器缓存。](#LambdaRedis.step1)
+ [步骤 2：为创建一个 Lambda 函数 ElastiCache](#LambdaRedis.step2)
+ [第 3 步：使用以下命令测试 Lambda 函数 ElastiCache](#LambdaRedis.step3)
+ [步骤 4：清除（可选）](#LambdaRedis.step4)

## 步骤 1：创建 ElastiCache 无服务器缓存。
<a name="LambdaRedis.step1"></a>

要创建无服务器缓存，请按照以下步骤操作。

### 步骤 1.1：创建无服务器缓存
<a name="LambdaRedis.step1.1"></a>

在此步骤中，您将使用 (CLI) 在账户的 us-east-1 区域的默认 Amazon VPC 中创建无服务器缓存。AWS Command Line Interface有关使用 ElastiCache 控制台或 API 创建无服务器缓存的信息，请参阅[创建 Redis OSS 无服务器缓存](GettingStarted.serverless-redis.step1.md)。

```
aws elasticache create-serverless-cache \
  --serverless-cache-name cache-01  \
--description "ElastiCache IAM auth application" \
--engine valkey
```

请注意，“状态”字段的值设置为 `CREATING`。可能需要一分钟 ElastiCache 才能完成缓存的创建。

### 步骤 1.2：复制无服务器缓存端点
<a name="LambdaRedis.step1.2"></a>

 ElastiCache 使用`describe-serverless-caches`命令验证 Redis 的 OSS 是否已完成缓存的创建。

```
aws elasticache describe-serverless-caches \
--serverless-cache-name cache-01
```

复制输出中显示的端点地址。在为 Lambda 函数创建部署包时，您将需要此地址。

### 步骤 1.3：创建 IAM 角色
<a name="LambdaRedis.step1.3"></a>



1. 为您的角色创建 IAM 信任政策文档，如下所示，允许您的账户承担新角色。将策略保存到名为 *trust-policy.json* 的文件中。

------
#### [ JSON ]

****  

   ```
   {
   "Version":"2012-10-17",		 	 	 
       "Statement": [{
           "Effect": "Allow",
           "Action": "sts:AssumeRole",
           "Resource": "arn:aws:iam::*:role/*"
       },
       {
         "Effect": "Allow",
         "Action": "sts:AssumeRole",
         "Resource": "arn:aws:iam::*:role/*"
       }]
   }
   ```

------

1. 创建 IAM 策略文档，如下所示。将策略保存到名为 *policy.json* 的文件中。

------
#### [ JSON ]

****  

   ```
   {
   "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
   "Effect" : "Allow",
         "Action" : [
           "elasticache:Connect"
         ],
         "Resource" : [
           "arn:aws:elasticache:us-east-1:123456789012:serverlesscache:cache-01",
           "arn:aws:elasticache:us-east-1:123456789012:user:iam-user-01"
         ]
       }
     ]
   }
   ```

------

1. 创建 IAM 角色。

   ```
   aws iam create-role \
   --role-name "elasticache-iam-auth-app" \
   --assume-role-policy-document file://trust-policy.json
   ```

1. 创建 IAM 策略。

   ```
   aws iam create-policy \
     --policy-name "elasticache-allow-all" \
     --policy-document file://policy.json
   ```

1. 向角色附加 IAM 策略。

   ```
   aws iam attach-role-policy \
    --role-name "elasticache-iam-auth-app" \
    --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"
   ```

### 步骤 1.4：创建默认用户
<a name="LambdaRedis.step1.4"></a>

1. 创建新的默认用户。

   ```
   aws elasticache create-user \
     --user-name default \
   --user-id default-user-disabled \
   --engine redis \
   --authentication-mode Type=no-password-required \
   --access-string "off +get ~keys*"
   ```

1. 创建启用 IAM 的新用户。

   ```
   aws elasticache create-user \
     --user-name iam-user-01 \
   --user-id iam-user-01 \
   --authentication-mode Type=iam \
   --engine redis \
   --access-string "on ~* +@all"
   ```

1. 创建用户组并附加用户。

   ```
   aws elasticache create-user-group \
     --user-group-id iam-user-group-01 \
   --engine redis \
   --user-ids default-user-disabled iam-user-01
   
   aws elasticache modify-serverless-cache \
     --serverless-cache-name cache-01  \
   --user-group-id iam-user-group-01
   ```

## 步骤 2：为创建一个 Lambda 函数 ElastiCache
<a name="LambdaRedis.step2"></a>

要创建 Lambda 函数来访问 ElastiCache 缓存，请执行以下步骤。

### 步骤 2.1：创建 Lambda 函数
<a name="LambdaRedis.step2.1"></a>

在本教程中，我们为您的 Lambda 函数提供了 Python 中的示例代码。

**Python**

以下示例 Python 代码读取项目并将其写入 ElastiCache 缓存。复制代码，并将其保存到名为 `app.py` 的文件中。请确保将代码中的 `elasticache_endpoint` 值替换为您在之前的步骤中复制的端点地址。

```
from typing import Tuple, Union
from urllib.parse import ParseResult, urlencode, urlunparse

import botocore.session
import redis
from botocore.model import ServiceId
from botocore.signers import RequestSigner
from cachetools import TTLCache, cached
import uuid

class ElastiCacheIAMProvider(redis.CredentialProvider):
    def __init__(self, user, cache_name, is_serverless=False, region="us-east-1"):
        self.user = user
        self.cache_name = cache_name
        self.is_serverless = is_serverless
        self.region = region

        session = botocore.session.get_session()
        self.request_signer = RequestSigner(
            ServiceId("elasticache"),
            self.region,
            "elasticache",
            "v4",
            session.get_credentials(),
            session.get_component("event_emitter"),
        )

    # Generated IAM tokens are valid for 15 minutes
    @cached(cache=TTLCache(maxsize=128, ttl=900))
    def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
        query_params = {"Action": "connect", "User": self.user}
        if self.is_serverless:
            query_params["ResourceType"] = "ServerlessCache"
        url = urlunparse(
            ParseResult(
                scheme="https",
                netloc=self.cache_name,
                path="/",
                query=urlencode(query_params),
                params="",
                fragment="",
            )
        )
        signed_url = self.request_signer.generate_presigned_url(
            {"method": "GET", "url": url, "body": {}, "headers": {}, "context": {}},
            operation_name="connect",
            expires_in=900,
            region_name=self.region,
        )
        # RequestSigner only seems to work if the URL has a protocol, but
        # Elasticache only accepts the URL without a protocol
        # So strip it off the signed URL before returning
        return (self.user, signed_url.removeprefix("https://"))

def lambda_handler(event, context):
    username = "iam-user-01" # replace with your user id
    cache_name = "cache-01" # replace with your cache name
    elasticache_endpoint = "cache-01-xxxxx.serverless.use1.cache.amazonaws.com" # replace with your cache endpoint
    creds_provider = ElastiCacheIAMProvider(user=username, cache_name=cache_name, is_serverless=True)
    redis_client = redis.Redis(host=elasticache_endpoint, port=6379, credential_provider=creds_provider, ssl=True, ssl_cert_reqs="none")
    
    key='uuid'
    # create a random UUID - this will be the sample element we add to the cache
    uuid_in = uuid.uuid4().hex
    redis_client.set(key, uuid_in)
    result = redis_client.get(key)
    decoded_result = result.decode("utf-8")
    # check the retrieved item matches the item added to the cache and print
    # the results
    if decoded_result == uuid_in:
        print(f"Success: Inserted {uuid_in}. Fetched {decoded_result} from Valkey.")
    else:
        raise Exception(f"Bad value retrieved. Expected {uuid_in}, got {decoded_result}")
        
    return "Fetched value from Valkey"
```

此代码使用 Python redis-py 库将项目放入缓存并检索它们。此代码使用 cachetools 将生成的 IAM 身份验证令牌缓存 15 分钟。要创建包含 redis-py 和 cachetools 的部署包，请执行以下步骤。

在包含 app.py 源代码文件的项目目录中，创建一个文件夹包，用于在其中安装 redis-py 和 cachetools 库。

```
mkdir package
```

使用 pip 安装 redis-py、cachetools。

```
pip install --target ./package redis
pip install --target ./package cachetools
```

创建包含 redis-py 和 cachetools 库的 zip 文件。在 Linux 和 macOS 中，运行以下命令：在 Windows 中，使用首选 zip 实用工具创建一个 .zip 文件，并将 redis-py 和 cachetools 库置于根目录下。

```
cd package
zip -r ../my_deployment_package.zip .
```

将您的函数代码添加到 .zip 文件。在 Linux 和 macOS 中，运行以下命令：在 Windows 中，使用首选 zip 实用工具将 app.py 添加到 .zip 文件的根目录下。

```
cd ..
zip my_deployment_package.zip app.py
```

### 步骤 2.2：创建 IAM 角色（执行角色）
<a name="LambdaRedis.step2.2"></a>

将名为的AWS托管策略附加`AWSLambdaVPCAccessExecutionRole`到该角色。

```
aws iam attach-role-policy \
 --role-name "elasticache-iam-auth-app" \
 --policy-arn "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
```

### 步骤 2.3：上传部署包（创建 Lambda 函数）
<a name="LambdaRedis.step2.3"></a>

在此步骤中，您将使用创建函数命令创建 Lambda 函数 (AccessValkey)。AWS CLI

在包含您的部署包 .zip 文件的项目目录中，运行以下 Lambda CLI `create-function` 命令。

对于角色选项，请使用您在上一步中创建的执行角色的 ARN。对于 vpc-config，请输入默认 VPC 子网的列表和默认 VPC 安全组 ID 的列表，以逗号分隔。您还可以在 Amazon VPC 控制台中找到这些值。要查找您的默认 VPC 子网，请选择**您的 VPCs**，然后选择您AWS账户的默认 VPC。要查找此 VPC 的安全组，请转到**安全**，然后选择**安全组**。请确保您选择了 us-east-1 区域。

```
aws lambda create-function \
--function-name AccessValkey  \
--region us-east-1 \
--zip-file fileb://my_deployment_package.zip \
--role arn:aws:iam::123456789012:role/elasticache-iam-auth-app \
--handler app.lambda_handler \
--runtime python3.12  \
--timeout 30 \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=default-security-group-id
```

## 第 3 步：使用以下命令测试 Lambda 函数 ElastiCache
<a name="LambdaRedis.step3"></a>

在此步骤中，您将使用调用命令手动调用 Lambda 函数。当 Lambda 函数执行时，它会生成一个 UUID 并将其写入您在 Lambda 代码中指定的 ElastiCache 缓存中。然后，Lambda 函数将从缓存中检索项目。

1. 使用调用命令AWS Lambda调用 Lambda 函数 (AccessValkey)。

   ```
   aws lambda invoke \
   --function-name AccessValkey  \
   --region us-east-1 \
   output.txt
   ```

1. 按以下过程验证 Lambda 函数是否已成功执行：
   + 查看 output.txt 文件。
   + 打开 CloudWatch 控制台并选择函数的日志组 (/aws/lambda/AccessValkey)，验证日志中的 CloudWatch 结果。日志流应包含类似于以下内容的输出：

     ```
     Success: Inserted 826e70c5f4d2478c8c18027125a3e01e. Fetched 826e70c5f4d2478c8c18027125a3e01e from Valkey.
     ```
   + 在AWS Lambda控制台中查看结果。

## 步骤 4：清除（可选）
<a name="LambdaRedis.step4"></a>

要进行清理，请执行以下步骤。

### 步骤 4.1：删除 Lambda 函数
<a name="LambdaRedis.step4.1"></a>

```
aws lambda delete-function \
 --function-name AccessValkey
```

### 步骤 4.2：删除无服务器缓存
<a name="LambdaRedis.step4.2"></a>

删除缓存。

```
aws elasticache delete-serverless-cache \
 --serverless-cache-name cache-01
```

移除用户和用户组。

```
aws elasticache delete-user \
 --user-id default-user-disabled

aws elasticache delete-user \
 --user-id iam-user-01

aws elasticache delete-user-group \
 --user-group-id iam-user-group-01
```

### 步骤 4.3：移除 IAM 角色和策略
<a name="LambdaRedis.step4.3"></a>

```
aws iam detach-role-policy \
 --role-name "elasticache-iam-auth-app" \
 --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"
 
aws iam detach-role-policy \
--role-name "elasticache-iam-auth-app" \
--policy-arn "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
 
aws iam delete-role \
 --role-name "elasticache-iam-auth-app"
  
 aws iam delete-policy \
  --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"
```