この記事では、Python 言語で Azure Redis Cache を使用し、Microsoft Entra ID を使用して接続する方法について説明します。
[前提条件]
- Azure サブスクリプション - 無料アカウントを作成する
- Python 3.7 以降の言語環境をインストールする
- これらのインポートをプロジェクトと開発環境に追加する
redis
- Redis Python クライアントredis-entraid
- Redis Microsoft Entra ID 認証拡張機能azure-identity
- Azure 認証ライブラリ
Azure Managed Redis インスタンスを作成する
まず、キャッシュを作成します。 Azure Portal を使用して、Azure Managed Redis または Azure Cache for Redis を使用してキャッシュを作成できます。 このクイック スタートでは、Azure Managed Redis を使用します。
キャッシュを作成すると、Microsoft Entra ID が既定で有効になり、最初からセキュリティで保護されます。 キャッシュでは、このクイック スタート用のパブリック エンドポイントも使用する必要があります。
ポータルでキャッシュを作成するには、次のいずれかの手順に従います。
必要に応じて、Azure CLI の PowerShell を使用して任意のキャッシュを作成できます。
Redis Cache に接続するコード
コード サンプルの最初の部分で、キャッシュへの接続を設定します。
- Azure Managed Redis および Enterprise キャッシュのポート: 10000
- Azure Cache for Redis インスタンスのポート: 6380
import redis
from azure.identity import DefaultAzureCredential
from redis_entraid.cred_provider import create_from_default_azure_credential
# Connection details for your cache
# Get the connection details for the Redis instance
redis_host = "contosob116.westus3.redis.azure.net"
redis_port = 10000 #For an Azure
print("🚀 Starting Azure Redis Cache connection test...")
print(f"📡 Connecting to: {redis_host}:{redis_port}")
# Validate configuration
if not redis_host or not redis_port:
print("❌ Error: Redis host and port must be configured")
exit(1)
print() # Add a new line
try:
# Create credential provider using DefaultAzureCredential for Azure Entra ID authentication
credential_provider = create_from_default_azure_credential(
("https://redis.azure.com/.default",),)
# Create a Redis client with Azure Entra ID authentication
r = redis.Redis(host=redis_host,
port=redis_port,
ssl=True,
decode_responses=True,
credential_provider=credential_provider,
socket_timeout=10,
socket_connect_timeout=10
)
接続をテストするコード
次のセクションでは、ping
値を返す Redis コマンド True
を使用して接続をテストします。
# Ping the Redis server to test the connection
result = r.ping()
if result:
print("Ping returned: ", result)
コードでキーを設定し、キーを取得する
このセクションでは、基本的な set
と get
シーケンスを使用して、最も簡単な方法で Redis キャッシュの使用を開始します。
# Create a simple set and get operation
result = r.set("Message", "Hello, The cache is working with Python!")
print("✅ SET Message succeeded: " + str(result))
print() # Add a new line
value = r.get("Message")
if value is not None:
print("✅ GET Message returned : " + str(value))
print() # Add a new line
else:
print("⚠️ GET Message returned None")
print() # Add a new line
print("🎉 All Redis operations completed successfully!")
print() # Add a new line
このコードを実行する前に、自分を Redis ユーザーとしてキャッシュに追加する必要があります。
また、Azure コマンド ラインまたは Azure 開発者コマンド ライン (azd) を使用して、コマンド ラインから Azure への接続を承認する必要があります。
また、 キャッシュにユーザーまたはシステム プリンシパルを追加する必要があります。 プログラムを実行する可能性のあるすべてのユーザーを Redis Cache でユーザーとして追加します。
結果は次のようになります。
C:\utils\python-quickstart>python quickstart-amr.py
🚀 Starting Azure Redis Cache connection test...
📡 Connecting to: contosob116.westus3.redis.azure.net:10000
✅ Ping returned : True
✅ SET Message succeeded: True
✅ GET Message returned : Hello, The cache is working with Python!
🎉 All Redis operations completed successfully!
🔐 Redis connection closed
ここでは、このコード サンプル全体を確認できます。 このコードには、わかりやすくするために、前のコードの説明から省略されたエラー チェックがいくつか含まれています。 最後の手順では、キャッシュへの接続を閉じます。
# Python Quickstart using Azure Entra ID authentication
# Azure Managed Redis cache that you created using the Azure portal, or CLI
# This script demonstrates secure connection using Microsoft Entra ID authentication
# This script demonstrates secure connection using the default Azure credential provider
# You should be a user on the cache and logged in to Azure CLI with the same account using `az login`
import redis
from azure.identity import DefaultAzureCredential
from redis_entraid.cred_provider import create_from_default_azure_credential
# Connection details for your cache
# Get the connection details for the Redis instance
redis_host = "<host-url>" # Replace with your cache info
redis_port = <port number> # Replace with your cache info
print("🚀 Starting Azure Redis Cache connection test...")
print(f"📡 Connecting to: {redis_host}:{redis_port}")
# Validate configuration
if not redis_host or not redis_port:
print("❌ Error: Redis host and port must be configured")
exit(1)
print() # Add a new line
try:
# Create credential provider using DefaultAzureCredential for Azure Entra ID authentication
credential_provider = create_from_default_azure_credential(
("https://redis.azure.com/.default",),)
# Create a Redis client with Azure Entra ID authentication
r = redis.Redis(host=redis_host,
port=redis_port,
ssl=True,
decode_responses=True,
credential_provider=credential_provider,
socket_timeout=10,
socket_connect_timeout=10
)
# Test connection
result = r.ping()
print("✅ Ping returned : " + str(result))
print() # Add a new line
# Create a simple set and get operation
result = r.set("Message", "Hello, The cache is working with Python!")
print("✅ SET Message succeeded: " + str(result))
print() # Add a new line
value = r.get("Message")
if value is not None:
print("✅ GET Message returned : " + str(value))
print() # Add a new line
else:
print("⚠️ GET Message returned None")
print() # Add a new line
print("🎉 All Redis operations completed successfully!")
print() # Add a new line
except redis.ConnectionError as e:
print(f"❌ Connection error: {e}")
print("💡 Check if Redis host and port are correct, and ensure network connectivity")
print() # Add a new line
except redis.AuthenticationError as e:
print(f"❌ Authentication error: {e}")
print("💡 Check if Azure Entra ID authentication is properly configured")
print() # Add a new line
except redis.TimeoutError as e:
print(f"❌ Timeout error: {e}")
print("💡 Check network latency and Redis server performance")
print() # Add a new line
except Exception as e:
print(f"❌ Unexpected error: {e}")
if "999" in str(e):
print("💡 Error 999 typically indicates a network connectivity issue or firewall restriction")
print(" - Verify the Redis hostname is correct")
print(" - Verify that you have logged in with Az CLI")
print(" - Ensure the Redis cache is running and accessible")
print() # Add a new line
finally:
# Clean up connection if it exists
if 'r' in locals():
try:
r.close()
print("🔐 Redis connection closed")
except Exception as e:
print(f"❌ Error closing connection: {e}")
リソースをクリーンアップする
この記事で作成したリソースを引き続き使用する場合は、リソース グループを保持します。
それ以外の場合、リソースを使い終わったら、課金されないように、作成した Azure リソース グループを削除できます。
重要
リソース グループを削除すると、元に戻すことができません。 リソース グループを削除すると、そのリソース グループ内のすべてのリソースは完全に削除されます。 間違ったリソース グループやリソースをうっかり削除しないようにしてください。 リソースを既存のリソース グループ内に作成し、そのリソース グループ内に保持したいリソースが含まれている場合は、リソース グループを削除するのではなく、各リソースを個別に削除できます。
リソース グループを削除するには
Azure portal にサインインし、 [リソース グループ] を選択します。
削除するリソース グループを選択します。
多数のリソース グループがある場合は、[任意のフィールドのフィルター...] ボックスを使用し、この記事用に作成したリソース グループの名前を入力します。 結果リストでリソース グループを選びます。
[リソース グループの削除] を選択します。
リソース グループの削除の確認を求めるメッセージが表示されます。 確認のためにリソース グループの名前を入力し、[削除] を選択します。
しばらくすると、リソース グループとそのリソースのすべてが削除されます。