

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon 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/signup](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和建立管理使用者，以免將根使用者用於日常任務。

**保護您的AWS 帳戶根使用者**

1.  選擇**根使用者**並輸入AWS 帳戶您的電子郵件地址，以帳戶擁有者[AWS 管理主控台](https://console.aws.amazon.com/)身分登入 。在下一頁中，輸入您的密碼。

   如需使用根使用者登入的說明，請參閱 *AWS 登入使用者指南*中的[以根使用者身分登入](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 若要在您的根使用者帳戶上啟用多重要素驗證 (MFA)。

   如需說明，請參閱《*IAM 使用者指南*》中的[為您的AWS 帳戶根使用者 （主控台） 啟用虛擬 MFA 裝置](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**建立具有管理存取權的使用者**

1. 啟用 IAM Identity Center。

   如需指示，請參閱《AWS IAM Identity Center使用者指南》**中的[啟用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 目錄做為身分來源的教學課程，請參閱*AWS IAM Identity Center《 使用者指南*》中的[使用預設值設定使用者存取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使用者指南》**中的[建立許可集](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 將使用者指派至群組，然後對該群組指派單一登入存取權。

   如需指示，請參閱《AWS IAM Identity Center使用者指南》**中的[新增群組](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 授與程式設計存取權
<a name="elasticache-set-up-access-key"></a>

如果使用者想要與AWS外部互動，則需要程式設計存取AWS 管理主控台。授予程式設計存取權的方式取決於正在存取的使用者類型AWS。

若要授予使用者程式設計存取權，請選擇下列其中一個選項。


****  

| 哪個使用者需要程式設計存取權？ | 到 | 根據 | 
| --- | --- | --- | 
| IAM | （建議） 使用主控台登入資料做為臨時登入資料，以簽署對AWS CLI、AWS SDKs程式設計請求。AWS APIs |  請依照您要使用的介面所提供的指示操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/AmazonElastiCache/latest/dg/set-up.html)  | 
|  人力資源身分 (IAM Identity Center 中管理的使用者)  | 使用暫時登入資料簽署對AWS CLI、AWS SDKs程式設計請求。AWS APIs |  請依照您要使用的介面所提供的指示操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/AmazonElastiCache/latest/dg/set-up.html)  | 
| IAM | 使用暫時登入資料簽署對AWS CLI、AWS SDKs程式設計請求。AWS APIs | 遵循《IAM 使用者指南》中[將臨時登入資料與AWS資源](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)搭配使用的指示。 | 
| IAM | (不建議使用)使用長期登入資料來簽署對AWS CLI、AWS SDKs程式設計請求。AWS APIs |  請依照您要使用的介面所提供的指示操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 節點型叢集針對 Valkey 和 Redis OSS 命令使用連接埠 6379，而 ElastiCache Serverless 同時使用連接埠 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 使用，否則此安全群組將會命名為 *default*。

1. 選擇「傳入」索引標籤，然後：

   1. 選擇**編輯**。

   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 (自訂 TCP 規則)**。

   1. 如果使用 ElastiCache for Redis OSS，請在**連接埠範圍**方塊中輸入 `6380`。

      如果使用 ElastiCache for Memcached，請在**連接埠範圍**方塊中輸入 `11212`。

   1. 在**來源**方塊中，選擇具有連接埠範圍 (0.0.0.0/0) 的**隨處**，讓任何您在 Amazon VPC 內啟動的 Amazon EC2 執行個體都能連線至您的快取。

   1. 選擇**儲存**

## 下載並設定命令列存取
<a name="Download-and-install-cli"></a>

**下載並安裝 *valkey-cli* 公用程式。**

如果您使用 ElastiCache for Valkey，您可能會發現 valkey-cli 公用程式很有用。如果您使用 ElastiCache for Redis OSS 搭配 redis-cli，請考慮切換到 valkey-cli，因為它也適用於 Redis OSS。

1. 使用您選擇的連線公用程式連線到 Amazon EC2 執行個體。如需如何連線到 Amazon EC2 執行個體的說明，請參閱 [Amazon 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 的建置支援。只有在 TLS 已啟用的情況下，才能存取 ElastiCache Serverless。
如果您要連線至未加密的叢集，則不需要 `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 存取和安全群組設定，並在 EC2 執行個體上設定 valkey-cli。如需該步驟的詳細資訊，請參閱 [設定 ElastiCache](set-up.md)。

除了下列步驟之外，如果您有大型或全域應用程式，可以透過建立和讀取複本來大幅提高讀取效能。如需此更進階步驟的詳細資訊，請參閱 [使用僅供讀取複本的最佳實務](ReadReplicas.md)。

**尋找您的快取端點**

**AWS 管理主控台**

使用 ElastiCache 主控台尋找您的快取端點：

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon 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 OSS 目錄，然後執行 命令 （注意：將 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 管理主控台 ，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon 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 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) 的 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 存取和安全群組設定，並在 EC2 執行個體上設定 valkey-cli。如需該步驟的詳細資訊，請參閱 [設定 ElastiCache](set-up.md)。

**尋找您的快取端點**

**AWS 管理主控台**

使用 ElastiCache 主控台尋找您的快取端點：

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon 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 管理主控台 ，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon 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 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) 的 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/)。

根據預設，ElastiCache 會在您的預設 VPC 中建立快取。請確認您的 EC2 執行個體同樣是在預設 VPC 中建立，如此它才能連線至快取。

**尋找您的快取端點**

**AWS 管理主控台**

使用 ElastiCache 主控台尋找您的快取端點：

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon 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\$1started.html](https://pymemcache.readthedocs.io/en/latest/getting_started.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 memcache) 進行連線
<a name="w2aac14c21c41c29b9"></a>

請參閱 [https://github.com/electrode-io/memcache](https://github.com/electrode-io/memcache) 和 [https://www.npmjs.com/package/memcache-client](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-memcache](https://github.com/aisk/rust-memcache)。

```
// 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/gomemcache](https://github.com/bradfitz/gomemcache)

```
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 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 在 ElastiCache 主控台儀表板中，選擇在要刪除的快取上執行的引擎。接著會出現執行該引擎的所有快取清單。

1. 若要選擇要刪除的快取，請從快取清單中選擇快取的名稱。
**重要**  
 您一次只能從 ElastiCache 主控台刪除一個快取。選擇多個快取會停用刪除操作。

1. 對於 **Actions** (動作)，請選擇 **Delete** (刪除)。

1. 在**刪除快取**確認畫面中，選擇**刪除**以刪除快取，或選擇**取消**以保留叢集。

1. 如果您選擇**刪除**，快取的狀態就會變更為*正在刪除*。

一旦您的快取進入**刪除中**狀態，就不會再對您收費。

**使用AWS CLI**

下列程式碼會刪除 my-cache 快取。

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

delete-serverless-cache CLI 動作只會刪除一個無伺服器快取。若要刪除多個快取，請針對您要刪除的每個無伺服器快取呼叫 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
```

如需詳細資訊，請參閱AWS CLI for 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 和 Redis OSS。我們鼓勵您遵循其中一個特定語言的教學。

**注意**  
AWS SDKs適用於各種語言。如需取得完整清單，請參閱 [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 for Redis OSS 叢集 （啟用叢集模式和停用叢集模式）
+ 檢查使用者或使用者群組是否存在，否則請建立。（此功能適用於 Valkey 7.2 及更新版本，以及 Redis OSS 6.0 至 7.1。)
+ 連線至 ElastiCache
+ 執行各種作業，例如設定和取得字串、讀取和寫入串流，以及從發佈/訂閱頻道發佈和訂閱。

當您完成本教學課程時，您可以參考適用於 Python (Boto) 的AWS SDK 文件。下一節為 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 SDK for ElastiCache for Redis OSS 管理操作 （叢集或使用者建立） 和 redis-py/redis-py-cluster 進行資料處理。

**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)
+ [檢查使用者/使用者群組是否存在，若不存在則加以建立](#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>

為了確保安全性，您可以在建立停用叢集模式的叢集時，使用 Transport Layer Security (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>

為了確保安全性，您可以在建立啟用叢集模式的叢集時，使用 Transport Layer Security (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)。

### 檢查使用者/使用者群組是否存在，若不存在則加以建立
<a name="ElastiCache-Getting-Started-Tutorials-Users"></a>

使用 RBAC，您可以建立使用者，並使用存取字串將特定許可指派給他們。您可以將使用者指派給與特定角色 （管理員、人力資源） 一致的使用者群組，然後部署到一或多個 ElastiCache for 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>

下列範例使用適用於 ElastiCache 的 boto3 開發套件來使用 ElastiCache for Redis OSS。

**Topics**
+ [設定和取得字串](#ElastiCache-Getting-Started-Tutorials-set-strings)
+ [設定和取得具有多個項目的雜湊](#ElastiCache-Getting-Started-Tutorials-set-hash)
+ [從發佈/訂閱頻道發佈 (寫入) 和訂閱 (讀取)](#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`

### 從發佈/訂閱頻道發佈 (寫入) 和訂閱 (讀取)
<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：為 ElastiCache 建立 Lambda 函數](#LambdaRedis.step2)
+ [步驟 3：使用 ElastiCache 測試 Lambda 函數](#LambdaRedis.step3)
+ [步驟 4：清除 （選用）](#LambdaRedis.step4)

## 步驟 1：建立 ElastiCache 無伺服器快取。
<a name="LambdaRedis.step1"></a>

若要建立無伺服器快取，請遵循下列步驟。

### 步驟 1.1：建立無伺服器快取
<a name="LambdaRedis.step1.1"></a>

在此步驟中，您會使用AWS Command Line Interface(CLI) 在帳戶中 us-east-1 區域中的預設 Amazon VPC 中建立無伺服器快取。如需使用 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 for Redis OSS 已完成使用 `describe-serverless-caches`命令建立快取。

```
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：為 ElastiCache 建立 Lambda 函數
<a name="LambdaRedis.step2"></a>

若要建立 Lambda 函數以存取 ElastiCache 快取，請執行下列步驟。

### 步驟 2.1：建立 Lambda 函數
<a name="LambdaRedis.step2.1"></a>

在本教學課程中，我們會在 Python 中提供 Lambda 函數的範例程式碼。

**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 公用程式，在根目錄建立具有 redis-py 和 cachetools 程式庫的 .zip 檔案。

```
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>

在此步驟中，您會使用 create-function AWS CLI命令建立 Lambda 函數 (AccessValkey)。

從包含部署套件 .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：使用 ElastiCache 測試 Lambda 函數
<a name="LambdaRedis.step3"></a>

在此步驟中，您會使用叫用命令手動叫用 Lambda 函數。當 Lambda 函數執行時，會產生 UUID，並將其寫入您在 Lambda 程式碼中指定的 ElastiCache 快取。然後 Lambda 函數從快取中取回項目。

1. 使用叫用命令叫用 Lambda 函數AWS Lambda(AccessValkey)。

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

1. 確認 Lambda 函數是否成功執行，如下：
   + 檢視 output.txt 檔案。
   + 開啟 CloudWatch 主控台並選擇函數的日誌群組 (/aws/lambda/AccessValkey)，以驗證 CloudWatch Logs 中的結果。日誌串流應包含類似以下的輸出內容：

     ```
     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"
```