快速入门:将 Azure Redis 缓存与 Python 配合使用Quickstart: Use Azure Cache for Redis with Python

在本快速入门中,会将 Azure Redis 缓存合并到 Python 应用中,以便能够访问 Azure 中的任何应用程序都可以访问的安全专用缓存。In this quickstart, you incorporate Azure Cache for Redis into a Python app to have access to a secure, dedicated cache that is accessible from any application within Azure.

先决条件Prerequisites

在 Azure 上创建 Azure Redis 缓存Create an Azure Cache for Redis on Azure

  1. 若要创建缓存,请首先登录到 Azure 门户To create a cache, first sign in to the Azure portal. 然后选择“创建资源” > “数据库” > “用于 Redis 的 Azure 缓存”。Then select Create a resource > Databases > Azure Cache for Redis.

    新建缓存

  2. 在“新建用于 Redis 的 Azure 缓存”中,配置新缓存的设置。In New Azure Cache for Redis, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 全局唯一名称Globally unique name 缓存名称。The cache name. 必须是 1 到 63 个字符的字符串,只能包含数字、字母和 - 字符。It must be a string between 1 and 63 characters and contain only numbers, letters, and the - character. 缓存名称的开头或末尾不能是 - 字符,并且连续的 - 字符无效。The cache name cannot start or end with the - character, and consecutive - characters are not valid.
    订阅Subscription 你的订阅Your subscription 要在其下创建此新的用于 Redis 的 Azure 缓存实例的订阅。The subscription under which this new Azure Cache for Redis instance is created.
    资源组Resource group TestResourcesTestResources 要在其中创建缓存的新资源组的名称。Name for the new resource group in which to create your cache. 通过将应用的所有资源都放在一个组中,可以一起管理它们。By putting all the resources for an app in a group, you can manage them together. 例如,删除资源组会删除与该应用关联的所有资源。For example, deleting the resource group deletes all resources that are associated with the app.
    位置Location 中国北部China North 选择将使用缓存的其他服务附近的区域Choose a region near to other services that will use your cache.
    定价层Pricing tier 基本 C0(250 MB 缓存)Basic C0 (250 MB Cache) 定价层决定可用于缓存的大小、性能和功能。The pricing tier determines the size, performance, and features that are available for the cache. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
    固定到仪表板Pin to dashboard 选定Selected 将新缓存固定到仪表板,使其容易被找到。Pin the new cache to your dashboard to make it easy to find.

    创建缓存

  3. 配置了新缓存设置后,选择“创建”。After the new cache settings are configured, select Create.

    创建缓存可能耗时几分钟。It can take a few minutes for the cache to be created. 若要检查状态,可以监视仪表板上的进度。To check the status, you can monitor the progress on the dashboard. 缓存在创建后会显示状态为“正在运行”,可供用户使用。After the cache has been created, it shows the status Running, and is ready for use.

    创建的缓存

使用 Azure 门户检索主机名、端口和访问密钥Retrieve host name, ports, and access keys by using the Azure portal

连接到某个 Azure Redis 缓存实例时,缓存客户端需要该缓存的主机名、端口和密钥。When connecting to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. 在某些客户端中,这些项的名称可能略有不同。Some clients might refer to these items by slightly different names. 可以在 Azure 门户中检索此信息。You can retrieve this information in the Azure portal.

检索访问密钥和主机名的步骤To retrieve the access keys and host name

  1. 若要使用 Azure 门户检索访问密钥,请转到你的缓存,然后选择“访问密钥” 。To retrieve the access keys by using the Azure portal, go to your cache and select Access keys.

    Azure Redis 缓存密钥

  2. 若要检索主机名和端口,请选择“属性”。 To retrieve the host name and ports, select Properties.

    Azure Redis 缓存属性

安装 redis-pyInstall redis-py

Redis-py 是 Azure Redis 缓存的 Python 接口。Redis-py is a Python interface to Azure Cache for Redis. 使用 Python 包工具 pip 安装 redis-py 包。Use the Python packages tool, pip, to install the redis-py package.

以下示例通过以提升的管理员权限运行的 Visual Studio 2019 开发人员命令提示使用 Python3 的 pip3 在 Windows 10 上安装 redis-py 包。The following example uses pip3 for Python3 to install the redis-py package on Windows 10 using a Visual Studio 2019 Developer Command prompt running with elevated Administrator privileges.

    pip3 install redis

安装 redis-py

从缓存中读取数据以及向其中写入数据Read and write to the cache

从命令行运行 Python 并使用缓存进行测试。Run Python and test using the cache from the command line. <Your Host Name><Your Access Key> 替换为 Azure Redis 缓存的值。Replace <Your Host Name> and <Your Access Key> with the values for your Azure Cache for Redis.

>>> import redis
>>> r = redis.StrictRedis(host='<Your Host Name>.redis.cache.chinacloudapi.cn',
        port=6380, db=0, password='<Your Access Key>', ssl=True)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

Important

对于 Redis 版本 3.0 或更高版本,强制执行 SSL 证书检查。For Redis version is 3.0 or higher, SSL certificate check is enforced. 连接到 Redis 时,必须显式设置 ssl_ca_certs。ssl_ca_certs must be explicitly set when connecting to Redis. 对于 RH Linux,ssl_ca_certs 可以在“/etc/pki/tls/certs/ca-bundle.crt”证书模块中找到。In case of RH Linux, ssl_ca_certs can be found in the "/etc/pki/tls/certs/ca-bundle.crt" certificate module.

创建 Python 脚本Create a Python script

创建一个名为 PythonApplication1.py 的新的脚本文本文件。Create a new script text file named PythonApplication1.py.

PythonApplication1.py 添加以下脚本并保存该文件。Add the following script to PythonApplication1.py and save the file. 该脚本将测试缓存访问。This script will test the cache access. <Your Host Name><Your Access Key> 替换为 Azure Redis 缓存的值。Replace <Your Host Name> and <Your Access Key> with the values for your Azure Cache for Redis.

import redis

myHostname = "<Your Host Name>.redis.cache.chinacloudapi.cn"
myPassword = "<Your Access Key>"

r = redis.StrictRedis(host=myHostname, port=6380,
                      password=myPassword, ssl=True)

result = r.ping()
print("Ping returned : " + str(result))

result = r.set("Message", "Hello!, The cache is working with Python!")
print("SET Message returned : " + str(result))

result = r.get("Message")
print("GET Message returned : " + result.decode("utf-8"))

result = r.client_list()
print("CLIENT LIST returned : ")
for c in result:
    print("id : " + c['id'] + ", addr : " + c['addr'])

使用 Python 运行该脚本。Run the script with Python.

完成的 Python 测试

清理资源Clean up resources

如果将继续学习下一教程,可以保留本快速入门中创建的资源,以便重复使用。If you will be continuing with another tutorial, you can keep the resources created in this quickstart and reuse them.

如果已完成快速入门示例应用程序,可以删除本快速入门中创建的 Azure 资源,以免产生费用。Otherwise, if you are finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

Important

删除资源组的操作不可逆,资源组以及其中的所有资源将被永久删除。Deleting a resource group is irreversible and that the resource group and all the resources in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果在现有资源组(其中包含要保留的资源)中为托管此示例而创建了相关资源,可从各自的边栏选项卡逐个删除这些资源,而不要删除资源组。If you created the resources for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually from their respective blades instead of deleting the resource group.

登录到 Azure 门户,并单击“资源组”。 Sign in to the Azure portal and click Resource groups.

在“按名称筛选...”文本框中键入资源组的名称 。In the Filter by name... textbox, type the name of your resource group. 本文的说明使用了名为 TestResources 的资源组。The instructions for this article used a resource group named TestResources. 在结果列表中的资源组上,单击“...”,然后单击“删除资源组” 。On your resource group in the result list, click ... then Delete resource group.

删除

系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 键入资源组的名称进行确认,然后单击“删除” 。Type the name of your resource group to confirm, and click Delete.

片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps