本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
步骤 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
的部署包,请执行以下步骤。
-
在包含
app.py
源代码文件的项目目录中,创建一个package
文件夹,用于在其中安装pymemacache
库。mkdir package
-
使用 pip 安装
pymemcache
。pip install --target ./package pymemcache
-
创建包含
pymemcache
库的 .zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用首选 zip 实用工具创建一个 .zip 文件,并将pymemache
库置于根目录下。cd package zip -r ../my_deployment_package.zip .
-
将您的函数代码添加到 .zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用您首选的 zip 实用工具将
app.py
添加到 .zip 文件的根目录下。cd .. zip my_deployment_package.zip app.py
下一步