이 문서에서는 Python 언어로 Azure Managed Redis 캐시를 사용하고 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 캐시에 연결하는 코드
코드 샘플의 첫 번째 부분에서 캐시에 대한 연결을 설정합니다.
- 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 명령을 사용하여 연결을 테스트하고, 그 결과 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 캐시에서 프로그램을 사용자로 실행할 수 있는 모든 사용자를 추가합니다.
결과는 다음과 같습니다.
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에 로그인한 다음, 리소스 그룹을 선택합니다.
삭제하려는 리소스 그룹을 선택합니다.
리소스 그룹이 많은 경우 필드 필터링... 상자를 사용하여 이 문서에 대해 만든 리소스 그룹의 이름을 입력합니다. 결과 목록에서 리소스 그룹을 선택합니다.
리소스 그룹 삭제를 선택합니다.
리소스 그룹 삭제를 확인하는 메시지가 표시됩니다. 리소스 그룹의 이름을 입력하여 확인한 다음, 삭제를 선택합니다.
잠시 후, 리소스 그룹 및 모든 해당 리소스가 삭제됩니다.