第 2 步:创建 Lambda 函数 - ElastiCache 适用于 Redis 的 Amazon
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

第 2 步:创建 Lambda 函数

要创建 Lambda 函数,请执行以下步骤。

步骤 2.1:创建 Lambda 函数

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

Python

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

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 Redis.") else: raise Exception(f"Bad value retrieved. Expected {uuid_in}, got {decoded_result}") return "Fetched value from Redis"

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

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

mkdir package

使用 pip 安装 redis-py、缓存工具。

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 角色(执行角色)

将名为的 Amazon 托管策略附加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 函数)

在此步骤中,您将使用创建函数命令创建 Lambda 函数 (AccessRedis)。 Amazon CLI

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

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

aws lambda create-function \ --function-name AccessRedis \ --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