Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Dalam artikel ini, Anda mempelajari cara menggunakan cache Azure Managed Redis dengan bahasa Python dan menyambungkan menggunakan ID Microsoft Entra.
Prasyarat
- Langganan Azure - buat akun secara gratis
- Menginstal lingkungan bahasa Python 3.7+
- Tambahkan impor ini dari ke proyek Anda dan ke lingkungan pengembangan Anda
-
redis- Klien Redis Python -
redis-entraid- Ekstensi autentikasi Redis Microsoft Entra ID -
azure-identity- Pustaka autentikasi Azure
-
Membuat instans terkelola Azure Redis
Pertama, buat cache. Anda dapat membuat cache menggunakan Azure Managed Redis atau Azure Cache for Redis menggunakan portal Microsoft Azure. Dalam Panduan Mulai Cepat ini, kami menggunakan Layanan Azure Managed Redis.
Saat Anda membuat cache, ID Microsoft Entra diaktifkan secara default membuatnya aman sejak awal. Cache Anda juga harus menggunakan titik akhir publik untuk Panduan Memulai Cepat ini.
Untuk membuat cache dengan portal, ikuti salah satu prosedur berikut:
- Azure Managed Redis
- Azure Cache for Redis
Secara opsional, Anda dapat membuat cache menggunakan Azure CLI, PowerShell, mana pun yang Anda inginkan.
Kode untuk menyambungkan ke cache Redis
Di bagian pertama sampel kode, atur koneksi Anda ke cache.
- Port untuk cache Azure Managed Redis dan Enterprise: 10000
- Port untuk instans 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
)
Kode untuk menguji koneksi
Di bagian berikutnya, uji koneksi menggunakan perintah ping Redis yang mengembalikan True nilai .
# Ping the Redis server to test the connection
result = r.ping()
if result:
print("Ping returned: ", result)
Kode mengatur kunci, mendapatkan kunci
Di bagian ini, gunakan urutan dasar set dan get, untuk mulai menggunakan cache Redis dengan cara paling sederhana.
# 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
Sebelum dapat menjalankan kode ini, Anda harus menambahkan diri Anda sebagai pengguna Redis ke cache.
Anda juga harus mengotorisasi koneksi Anda ke Azure dari baris perintah menggunakan baris perintah Azure atau baris perintah pengembang Azure (azd).
Anda juga harus menambahkan pengguna atau Prinsipal sistem ke cache Anda. Tambahkan siapa saja yang mungkin menjalankan program sebagai pengguna di cache Redis.
Hasilnya terlihat seperti ini:
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
Di sini, Anda dapat melihat sampel kode ini secara keseluruhan. Kode berisi beberapa pemeriksaan kesalahan yang dihilangkan dari penjelasan kode sebelumnya untuk kesederhanaan. Langkah terakhir adalah menutup koneksi ke cache.
# 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}")
Membersihkan sumber daya
Jika Anda ingin terus menggunakan sumber daya yang Anda buat di artikel ini, simpan grup sumber daya.
Jika tidak, jika Anda sudah selesai dengan sumber daya, Anda dapat menghapus grup sumber daya Azure yang Anda buat untuk menghindari biaya.
Penting
Penghapusan grup sumber daya tidak bisa dipulihkan. Ketika Anda menghapus grup sumber daya, semua sumber daya di dalamnya dihapus secara permanen. Pastikan Anda tidak salah menghapus grup sumber daya atau sumber daya secara tidak sengaja. Jika Anda membuat sumber daya di dalam grup sumber daya yang sudah ada yang berisi sumber daya yang ingin Anda simpan, Anda dapat menghapus setiap sumber daya satu per satu alih-alih menghapus grup sumber daya.
Untuk menghapus grup sumber daya
Masuk ke portal Azure, lalu pilih Grup sumber daya.
Pilih grup sumber daya yang ingin Anda hapus.
Jika ada banyak grup sumber daya, gunakan kotak Filter untuk bidang apa pun... , ketik nama grup sumber daya yang Anda buat untuk artikel ini. Pilih grup sumber daya dalam daftar hasil.
Pilih Hapus grup sumber daya.
Anda diminta untuk mengonfirmasi penghapusan grup sumber daya. Ketik nama grup sumber daya Anda lagi untuk mengonfirmasi, lalu pilih Hapus.
Setelah beberapa saat, grup sumber daya dan semua sumber dayanya akan dihapus.