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

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

步骤 2.1:创建部署包

目前 Lambda 函数的示例代码仅在 Python 中提供。

Python

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

import uuid import ssl from pymemcache.client.base import Client elasticache_config_endpoint = "serverlesscacheforlambda-ces85m.serverless.use1.cache.amazonaws.com" target_port = 11211 context = ssl.create_default_context() memcached_client = Client((elasticache_config_endpoint, target_port), tls_context=context) def lambda_handler(event, context): # create a random UUID - this will be the sample element we add to the cache uuid_in = uuid.uuid4().hex # put the UUID to the cache memcached_client.set("uuid", uuid_in, expire=500, noreply=False) # get the item (UUID) from the cache result = memcached_client.get("uuid") 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 Memcached.") else: raise Exception(f"Bad value retrieved. Expected {uuid_in}, got {decoded_result}") return "Fetched value from Memcached"

此代码使用 Python pymemcache 库将项目放入缓存并检索它们。要创建包含 pymemcache 的部署包,请执行以下步骤。

  1. 在包含 app.py 源代码文件的项目目录中,创建一个 package 文件夹,用于在其中安装 pymemacache 库。

    mkdir package
  2. 使用 pip 安装 pymemcache

    pip install --target ./package pymemcache
  3. 创建包含 pymemcache 库的 .zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用首选 zip 实用工具创建一个 .zip 文件,并将 pymemache 库置于根目录下。

    cd package zip -r ../my_deployment_package.zip .
  4. 将您的函数代码添加到 .zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用您首选的 zip 实用工具将 app.py 添加到 .zip 文件的根目录下。

    cd .. zip my_deployment_package.zip app.py

下一步

步骤 2.2:创建 IAM 角色(执行角色)