快速入門:在 Python 中使用 Azure Cache for RedisQuickstart: Use Azure Cache for Redis in Python

在本文中,您會將 Azure Cache for 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

建立 Azure Cache for Redis 執行個體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 name>.redis.cache.windows.netYour cache instance's host name will be <DNS name>.redis.cache.windows.net.
    訂用帳戶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.
    位置Location 下拉並選取位置。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. 如需詳細資訊,請參閱 Azure Cache for Redis 概觀For more information, see Azure Cache for Redis Overview.
  4. 選取 [網路] 索引標籤,或按一下頁面底部的 [網路] 按鈕。Select the Networking tab or click the Networking button at the bottom of the page.

  5. 在 [網路功能] 索引標籤中,選取您的連線方法。In the Networking tab, select your connectivity method.

  6. 選取頁面底部的 [下一步:進階] 索引標籤,或按一下頁面底部的 [下一步:進階] 按鈕。Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. 在基本或標準快取執行個體的 [進階] 索引標籤中,如果您想要啟用非 TLS 連接埠,請選取啟用切換。In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis 版本 4 或 6。

  8. 在高階快取執行個體的 [進階] 索引標籤中,設定非 TLS 連接埠、叢集和資料持續性的設定。In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. 選取頁面底部的 [下一步:標記] 索引標籤,或按一下頁面底部的 [下一步:標記] 按鈕。Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. 在 [標記] 索引標籤中,如果您想要分類資源,可以選擇性地輸入名稱和值。Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. 選取 [檢閱 + 建立]。Select Review + create. 您會移至 [檢閱 + 建立] 索引標籤,其中 Azure 會驗證您的組態。You're taken to the Review + create tab where Azure validates your configuration.

  12. 出現綠色的「通過驗證」訊息之後,請選取 [建立]。After the green Validation passed message appears, select Create.

建立快取需要一些時間。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 入口網站擷取主機名稱、連接埠和存取金鑰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 Cache for Redis 金鑰

  • 若要取得主機名稱和連接埠,請從快取的左側導覽中選取 [屬性] 。To get the host name and ports, from your cache left navigation, select Properties. 主機名稱的格式為 <DNS name>.redis.cache.windows.netThe host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Redis 快取屬性

安裝 redis-pyInstall redis-py

redis-py (英文) 是 Azure Cache for 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-pyThe following example used pip3 for Python 3 to install redis-py on Windows 10 from an Administrator command prompt.

將 redis-py Python 介面安裝至 Azure Cache for 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 Cache for Redis 執行個體的值。Replace <Your Host Name> and <Your Access Key> with the values from your Azure Cache for Redis instance. 您的主機名稱的格式 <DNS name>.redis.cache.windows.netYour host name is of the form <DNS name>.redis.cache.windows.net.

>>> 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'

重要

如果是 Azure Cache for Redis 3.0 版或更新版本,即會強制執行 TLS/SSL 憑證檢查。For Azure Cache for Redis version 3.0 or higher, TLS/SSL certificate check is enforced. 連線至 Azure Cache for Redis 時,必須明確設定 ssl_ca_certs。ssl_ca_certs must be explicitly set when connecting to Azure Cache for Redis. 如果是 RH Linux,則可於 /etc/pki/tls/certs/ca-bundle.crt 憑證模組中找到 ssl_ca_certs。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.pyCreate a new text file, add the following script, and save the file as PythonApplication1.py. <Your Host Name><Your Access Key> 取代為您 Azure Cache for Redis 執行個體的值。Replace <Your Host Name> and <Your Access Key> with the values from your Azure Cache for Redis instance. 您的主機名稱的格式 <DNS name>.redis.cache.windows.netYour host name is of the form <DNS name>.redis.cache.windows.net.

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.pyRun 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.

重要

刪除資源群組是無法回復的動作,而資源群組及其中的所有資源都會永久刪除。Deleting a resource group is irreversible, and the resource group and all the resources in it are permanently deleted. 如果您在想要保留的現有資源群組中建立了 Azure Cache for 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 Cache for Redis 的資源群組

後續步驟Next steps