快速入门:创建使用 Azure Redis 缓存的 Python 应用Quickstart: Create a Python app that uses Azure Cache for Redis

在本文中,会将 Azure Redis 缓存合并到 Python 应用中,以便能够访问 Azure 中的任何应用程序都可以访问的安全专用缓存。In this article, 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

创建用于 Redis 的 Azure 缓存实例Create an Azure Cache for Redis instance

  1. 若要创建缓存,请登录到 Azure 门户并选择“创建资源” 。To create a cache, sign in to the Azure portal and select Create a resource.

    选择“创建资源”

  2. 在“新建”页上选择“数据库”,然后选择“Azure Cache for Redis”。 On the New page, select Databases and then select Azure Cache for Redis.

    选择“Azure Cache for Redis”

  3. 在“新建 Redis 缓存”页上配置新缓存的设置。 On the New Redis Cache page, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 输入任何全局唯一的名称。Enter a globally unique name. 缓存名称必须是包含 1 到 63 个字符的字符串,只能包含数字、字母或连字符。The cache name must be a string between 1 and 63 characters that contains only numbers, letters, or hyphens. 该名称必须以数字或字母开头和结尾,且不能包含连续的连字符。The name must start and end with a number or letter, and can't contain consecutive hyphens. 缓存实例的主机名是 <DNS 名称>.redis.cache.chinacloudapi.cn 。 Your cache instance's host name will be <DNS name>.redis.cache.chinacloudapi.cn.
    订阅Subscription 单击下拉箭头并选择你的订阅。Drop down and select your subscription. 要在其下创建此新的 Azure Cache for Redis 实例的订阅。The subscription under which to create this new Azure Cache for Redis instance.
    资源组Resource group 单击下拉箭头并选择一个资源组,或者选择“新建”并输入新的资源组名称。 Drop down and select a resource group, or select Create new and enter a new resource group name. 要在其中创建缓存和其他资源的资源组的名称。Name for the resource group in which to create your cache and other resources. 将所有应用资源放入一个资源组可以轻松地统一管理或删除这些资源。By putting all your app resources in one resource group, you can easily manage or delete them together.
    LocationLocation 单击下拉箭头并选择一个位置。Drop down and select a location. 选择与要使用该缓存的其他服务靠近的区域Select a region near other services that will use your cache.
    定价层Pricing tier 单击下拉箭头并选择一个定价层Drop down and select a Pricing tier. 定价层决定可用于缓存的大小、性能和功能。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.
  4. 选择“创建” 。Select Create.

    创建 Azure Redis 缓存

    创建缓存需要花费片刻时间。It takes a while for the cache to create. 可以在 Azure Cache for Redis 的“概述”页上监视进度。 You can monitor progress on the Azure Cache for Redis Overview page. 如果“状态”显示为“正在运行”,则表示该缓存可供使用。 When Status shows as Running, the cache is ready to use.

    创建的 Azure Redis 缓存

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

若要连接到某个 Azure Cache for Redis 实例,缓存客户端需要该缓存的主机名、端口和密钥。To connect 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 get the host name, ports, and keys from the Azure portal.

  • 若要获取访问密钥,请在缓存的左侧导航中选择“访问密钥”。 To get the access keys, from your cache left navigation, select Access keys.

    Azure Redis 缓存密钥

  • 若要获取主机名和端口,请在缓存的左侧导航栏中选择“属性”。 To get the host name and ports, from your cache left navigation, select Properties. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。The host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

    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 from a command prompt.

下面的示例使用 Python 3 的 pip3 在 Windows 10 上从管理员命令提示符安装 redis-py 。The following example used pip3 for Python 3 to install redis-py on Windows 10 from an Administrator command prompt.

将 redis-py Python 接口安装到 Azure Redis 缓存

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

从命令行运行 Python,并使用下面的代码测试缓存。Run Python from the command line and test your cache by using the following code. <Your Host Name><Your Access Key> 替换为 Azure Redis 缓存实例中的值。Replace <Your Host Name> and <Your Access Key> with the values from your Azure Cache for Redis instance. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。Your host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

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

Important

对于 Azure Redis 缓存版本 3.0 或更高版本,强制执行 SSL 证书检查。For Azure Cache for Redis version 3.0 or higher, SSL certificate check is enforced. 连接到 Azure Redis 缓存时,必须显式设置 ssl_ca_certs。ssl_ca_certs must be explicitly set when connecting to Azure Cache for Redis. 对于 RedHat Linux,ssl_ca_certs 位于 /etc/pki/tls/certs/ca-bundle.crt 证书中 。For RedHat Linux, ssl_ca_certs are in the /etc/pki/tls/certs/ca-bundle.crt certificate module.

创建 Python 示例应用Create a Python sample app

创建新的文本文件,添加以下脚本,并将文件另存为 PythonApplication1.py 。Create a new text file, add the following script, and save the file as PythonApplication1.py. <Your Host Name><Your Access Key> 替换为 Azure Redis 缓存实例中的值。Replace <Your Host Name> and <Your Access Key> with the values from your Azure Cache for Redis instance. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。Your host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

import redis

myHostname = "<Your Host Name>"
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 运行 PythonApplication1.py 。Run PythonApplication1.py with Python. 应显示如以下示例所示的结果:You should see results like the following example:

运行 Python 脚本以测试缓存访问

清理资源Clean up resources

如果已完成在此快速入门中创建的 Azure 资源组和资源,则可以删除它们以避免产生费用。If you're finished with the Azure resource group and resources you created in this quickstart, you can delete them to avoid charges.

Important

删除资源组的操作不可逆,资源组以及其中的所有资源将被永久删除。Deleting a resource group is irreversible, and the resource group and all the resources in it are permanently deleted. 如果在要保留的现有资源组中创建了 Azure Redis 缓存实例,可从缓存“概述”页选择“删除”以便仅删除缓存 。If you created your Azure Cache for Redis instance in an existing resource group that you want to keep, you can delete just the cache by selecting Delete from the cache Overview page.

删除资源组及其 Azure Redis 缓存实例:To delete the resource group and its Redis Cache for Azure instance:

  1. Azure 门户中,搜索并选择“资源组” 。From the Azure portal, search for and select Resource groups.

  2. 在“按名称筛选”文本框中,输入包含缓存实例的资源组的名称,然后从搜索结果中选择它 。In the Filter by name text box, enter the name of the resource group that contains your cache instance, and then select it from the search results.

  3. 在资源组页上,选择“删除资源组” 。On your resource group page, select Delete resource group.

  4. 键入资源组名称,然后选择“删除” 。Type the resource group name, and then select Delete.

    删除 Azure Redis 缓存的资源组

后续步骤Next steps