azure-servicebus-py
โดย microsoft
การส่งข้อความระดับองค์กรสำหรับการสื่อสารบนคลาวด์ที่เชื่อถือได้ด้วยคิวและหัวข้อ pub/sub
npx skills add https://github.com/microsoft/agent-skills --skill azure-servicebus-pyAzure Service Bus SDK for Python
Enterprise messaging for reliable cloud communication with queues and pub/sub topics.
Installation
pip install azure-servicebus azure-identity
Environment Variables
SERVICEBUS_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net # Required for all auth methods
SERVICEBUS_QUEUE_NAME=myqueue # Required for queue operations
SERVICEBUS_TOPIC_NAME=mytopic # Required for topic operations
SERVICEBUS_SUBSCRIPTION_NAME=mysubscription # Required for subscription operations
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
Authentication & Lifecycle
🔑 Two rules apply to every code sample below:
- Prefer
DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
- Local dev:
DefaultAzureCredentialworks as-is.- Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.- Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
- Sync:
with <Client>(...) as client:- Async:
async with <Client>(...) as client:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.servicebus import ServiceBusClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
namespace = "<namespace>.servicebus.windows.net"
with ServiceBusClient(
fully_qualified_namespace=namespace,
credential=credential
) as client:
# Use client here (see following sections for operations)
...
Client Types
| Client | Purpose | Get From |
|---|---|---|
ServiceBusClient | Connection management | Direct instantiation |
ServiceBusSender | Send messages | client.get_queue_sender() / get_topic_sender() |
ServiceBusReceiver | Receive messages | client.get_queue_receiver() / get_subscription_receiver() |
Send Messages (Async)
import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
from azure.identity.aio import DefaultAzureCredential
async def send_messages():
credential = DefaultAzureCredential()
async with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=credential
) as client:
sender = client.get_queue_sender(queue_name="myqueue")
async with sender:
# Single message
message = ServiceBusMessage("Hello, Service Bus!")
await sender.send_messages(message)
# Batch of messages
messages = [ServiceBusMessage(f"Message {i}") for i in range(10)]
await sender.send_messages(messages)
# Message batch (for size control)
batch = await sender.create_message_batch()
for i in range(100):
try:
batch.add_message(ServiceBusMessage(f"Batch message {i}"))
except ValueError: # Batch full
await sender.send_messages(batch)
batch = await sender.create_message_batch()
batch.add_message(ServiceBusMessage(f"Batch message {i}"))
await sender.send_messages(batch)
asyncio.run(send_messages())
Receive Messages (Async)
async def receive_messages():
credential = DefaultAzureCredential()
async with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=credential
) as client:
receiver = client.get_queue_receiver(queue_name="myqueue")
async with receiver:
# Receive batch
messages = await receiver.receive_messages(
max_message_count=10,
max_wait_time=5 # seconds
)
for msg in messages:
print(f"Received: {str(msg)}")
await receiver.complete_message(msg) # Remove from queue
asyncio.run(receive_messages())
Receive Modes
| Mode | Behavior | Use Case |
|---|---|---|
PEEK_LOCK (default) | Message locked, must complete/abandon | Reliable processing |
RECEIVE_AND_DELETE | Removed immediately on receive | At-most-once delivery |
from azure.servicebus import ServiceBusReceiveMode
receiver = client.get_queue_receiver(
queue_name="myqueue",
receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE
)
Message Settlement
async with receiver:
messages = await receiver.receive_messages(max_message_count=1)
for msg in messages:
try:
# Process message...
await receiver.complete_message(msg) # Success - remove from queue
except ProcessingError:
await receiver.abandon_message(msg) # Retry later
except PermanentError:
await receiver.dead_letter_message(
msg,
reason="ProcessingFailed",
error_description="Could not process"
)
| Action | Effect |
|---|---|
complete_message() | Remove from queue (success) |
abandon_message() | Release lock, retry immediately |
dead_letter_message() | Move to dead-letter queue |
defer_message() | Set aside, receive by sequence number |
Topics and Subscriptions
# Send to topic
sender = client.get_topic_sender(topic_name="mytopic")
async with sender:
await sender.send_messages(ServiceBusMessage("Topic message"))
# Receive from subscription
receiver = client.get_subscription_receiver(
topic_name="mytopic",
subscription_name="mysubscription"
)
async with receiver:
messages = await receiver.receive_messages(max_message_count=10)
Sessions (FIFO)
# Send with session
message = ServiceBusMessage("Session message")
message.session_id = "order-123"
await sender.send_messages(message)
# Receive from specific session
receiver = client.get_queue_receiver(
queue_name="session-queue",
session_id="order-123"
)
# Receive from next available session
from azure.servicebus import NEXT_AVAILABLE_SESSION
receiver = client.get_queue_receiver(
queue_name="session-queue",
session_id=NEXT_AVAILABLE_SESSION
)
Scheduled Messages
from datetime import datetime, timedelta, timezone
message = ServiceBusMessage("Scheduled message")
scheduled_time = datetime.now(timezone.utc) + timedelta(minutes=10)
# Schedule message
sequence_number = await sender.schedule_messages(message, scheduled_time)
# Cancel scheduled message
await sender.cancel_scheduled_messages(sequence_number)
Dead-Letter Queue
from azure.servicebus import ServiceBusSubQueue
# Receive from dead-letter queue
dlq_receiver = client.get_queue_receiver(
queue_name="myqueue",
sub_queue=ServiceBusSubQueue.DEAD_LETTER
)
async with dlq_receiver:
messages = await dlq_receiver.receive_messages(max_message_count=10)
for msg in messages:
print(f"Dead-lettered: {msg.dead_letter_reason}")
await dlq_receiver.complete_message(msg)
Sync Client (for simple scripts)
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential
with ServiceBusClient(
fully_qualified_namespace="<namespace>.servicebus.windows.net",
credential=DefaultAzureCredential()
) as client:
with client.get_queue_sender("myqueue") as sender:
sender.send_messages(ServiceBusMessage("Sync message"))
with client.get_queue_receiver("myqueue") as receiver:
for msg in receiver:
print(str(msg))
receiver.complete_message(msg)
Best Practices
- Pick sync OR async and stay consistent. Do not mix
azure.xxxsync clients withazure.xxx.aioasync clients in the same call path. Choose one mode per module. - Always use context managers for clients and async credentials. Wrap every client in
with Client(...) as client:(sync) orasync with Client(...) as client:(async) for proper cleanup. For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up. - Use
DefaultAzureCredentialfor portable auth across local dev and Azure (avoid connection strings / API keys when possible). - Use async client for production workloads
- Complete messages after successful processing
- Use dead-letter queue for poison messages
- Use sessions for ordered, FIFO processing
- Use message batches for high-throughput scenarios
- Set
max_wait_timeto avoid infinite blocking
Reference Files
| File | Contents |
|---|---|
| references/patterns.md | Competing consumers, sessions, retry patterns, request-response, transactions |
| references/dead-letter.md | DLQ handling, poison messages, reprocessing strategies |
| scripts/setup_servicebus.py | CLI for queue/topic/subscription management and DLQ monitoring |
Skills เพิ่มเติมจาก microsoft
oss-growth
microsoft
บุคลิกภาพนักเติบโตโอเอสเอส
official
microsoft-foundry
microsoft
ปรับใช้ ประเมิน และจัดการ Foundry agents แบบครบวงจร: สร้าง Docker, push ไปยัง ACR, สร้าง hosted/prompt agent, เริ่ม container, batch eval, continuous eval, เวิร์กโฟลว์ prompt optimizer, agent.yaml, จัดชุดข้อมูลจาก traces ใช้สำหรับ: ปรับใช้ agent ไปยัง Foundry, hosted agent, สร้าง agent, เรียกใช้ agent, ประเมิน agent, รัน batch eval, continuous eval, การตรวจสอบต่อเนื่อง, สถานะ continuous eval, ปรับแต่ง prompt, ปรับปรุง prompt, prompt optimizer, ปรับแต่งคำแนะนำ agent, ปรับปรุง agent...
officialdevelopmentdevops
azure-ai
microsoft
ใช้สำหรับ Azure AI: ค้นหา, คำพูด, OpenAI, การประมวลผลเอกสารอัจฉริยะ ช่วยในการค้นหา, การค้นหาแบบเวกเตอร์/ไฮบริด, การแปลงคำพูดเป็นข้อความ, การแปลงข้อความเป็นคำพูด, การถอดเสียง, OCR เมื่อ: การค้นหา AI, การค้นหาคำถาม, การค้นหาแบบเวกเตอร์, การค้นหาแบบไฮบริด, การค้นหาเชิงความหมาย, การแปลงคำพูดเป็นข้อความ, การแปลงข้อความเป็นคำพูด, การถอดเสียง, OCR, แปลงข้อความเป็นคำพูด
officialdevelopmentapi
azure-deploy
microsoft
ดำเนินการปรับใช้ Azure สำหรับแอปพลิเคชันที่เตรียมไว้แล้วซึ่งมีไฟล์ .azure/deployment-plan.md และไฟล์โครงสร้างพื้นฐานอยู่แล้ว ห้ามใช้ทักษะนี้เมื่อผู้ใช้ขอสร้างแอปพลิเคชันใหม่ ให้ใช้ azure-prepare แทน ทักษะนี้รันคำสั่ง azd up, azd deploy, terraform apply และ az deployment พร้อมการกู้คืนข้อผิดพลาดในตัว ต้องมี .azure/deployment-plan.md จาก azure-prepare และสถานะที่ตรวจสอบแล้วจาก azure-validate เมื่อ: "run azd up", "run azd deploy", "execute deployment",...
officialdevopsaws
azure-storage
microsoft
บริการ Azure Storage รวมถึง Blob Storage, File Shares, Queue Storage, Table Storage และ Data Lake ตอบคำถามเกี่ยวกับระดับการเข้าถึงพื้นที่จัดเก็บ (hot, cool, cold, archive) ว่าเมื่อใดควรใช้แต่ละระดับ และการเปรียบเทียบระดับ ให้บริการจัดเก็บวัตถุ, แชร์ไฟล์ SMB, การส่งข้อความแบบอะซิงโครนัส, NoSQL key-value และการวิเคราะห์ข้อมูลขนาดใหญ่ รวมถึงการจัดการวงจรชีวิต ใช้สำหรับ: blob storage, file shares, queue storage, table storage, data lake, อัปโหลดไฟล์, ดาวน์โหลด blobs, storage accounts, access tiers,...
officialdevelopmentdatabase
azure-diagnostics
microsoft
ดีบักปัญหาการผลิตบน Azure โดยใช้ AppLens, Azure Monitor, สถานะทรัพยากร และการจัดลำดับความสำคัญอย่างปลอดภัย เมื่อ: ดีบักปัญหาการผลิต, แก้ไขปัญหาแอปบริการ, แอปบริการ CPU สูง, แอปบริการล้มเหลวในการปรับใช้, แก้ไขปัญหาคอนเทนเนอร์แอป, แก้ไขปัญหาฟังก์ชัน, แก้ไขปัญหา AKS, kubectl ไม่สามารถเชื่อมต่อ, kube-system/CoreDNS ล้มเหลว, pod รอ, crashloop, node ไม่พร้อม, การอัปเกรดล้มเหลว, วิเคราะห์บันทึก, KQL, ข้อมูลเชิงลึก, การดึงอิมเมจล้มเหลว, ปัญหาการเริ่มต้นเย็น, การตรวจสอบสถานะล้มเหลว,...
officialdevopsdevelopment
azure-prepare
microsoft
เตรียมแอปพลิเคชัน Azure สำหรับการปรับใช้ (infra Bicep/Terraform, azure.yaml, Dockerfiles) ใช้สำหรับสร้าง/ปรับปรุงให้ทันสมัย หรือสร้าง+ปรับใช้ ไม่ใช่สำหรับการย้ายข้ามคลาวด์ (ใช้ azure-cloud-migrate) ห้ามใช้สำหรับ: แอป copilot-sdk (ใช้ azure-hosted-copilot-sdk) เมื่อ: "สร้างแอป", "สร้างเว็บแอป", "สร้าง API", "สร้าง HTTP API แบบไร้เซิร์ฟเวอร์", "สร้างฟรอนต์เอนด์", "สร้างแบ็กเอนด์", "สร้างบริการ", "ปรับปรุงแอปพลิเคชันให้ทันสมัย", "อัปเดตแอปพลิเคชัน", "เพิ่มการรับรองความถูกต้อง", "เพิ่มการแคช", "โฮสต์บน Azure", "สร้างและ...
officialdevelopmentdevops
azure-validate
microsoft
การตรวจสอบความพร้อมก่อนการปรับใช้สำหรับ Azure ตรวจสอบเชิงลึกเกี่ยวกับการกำหนดค่า โครงสร้างพื้นฐาน (Bicep หรือ Terraform) การกำหนดบทบาท RBAC สิทธิ์ของ managed identity และข้อกำหนดเบื้องต้นก่อนการปรับใช้ เมื่อ: ตรวจสอบแอปของฉัน ตรวจสอบความพร้อมในการปรับใช้ เรียกใช้การตรวจสอบก่อนดำเนินการ ยืนยันการกำหนดค่า ตรวจสอบว่าพร้อมปรับใช้หรือไม่ ตรวจสอบ azure.yaml ตรวจสอบ Bicep ทดสอบก่อนปรับใช้ แก้ไขข้อผิดพลาดในการปรับใช้ ตรวจสอบ Azure Functions ตรวจสอบ function app ตรวจสอบ serverless...
officialdevopstesting