Python용 Service Bus 라이브러리Service Bus libraries for Python

Microsoft Azure Service Bus는 신뢰할 수 있는 메시지 큐 및 지속형 게시/구독 메시징을 포함하여 클라우드 기반, 메시지 지향 미들웨어 기술 집합을 지원합니다.Microsoft Azure Service Bus supports a set of cloud-based, message-oriented middleware technologies including reliable message queuing and durable publish/subscribe messaging.

v0.50.0의 새로운 기능What's new in v0.50.0?

0.50.0 버전부터 새 AMQP 기반 API는 메시지 보내기 및 받기를 할 수 있습니다.As of version 0.50.0 a new AMQP-based API is available for sending and receiving messages. 이 업데이트는 호환성이 손상되는 변경을 포함합니다.This update involves breaking changes.

현 시점에서 업그레이드가 적합한지 판단하려면 v0.21.1에서 v0.50.0로 마이그레이션을 읽어보세요.Please read Migration from v0.21.1 to v0.50.0 to determine if upgrading is right for you at this time.

새로운 AMQP 기반 API는 향상된 메시지 전달 신뢰성, 성능 및 향후 확장된 기능 지원을 제공합니다.The new AMQP-based API offers improved message passing reliability, performance and expanded feature support going forward. 새로운 API는 또한 메시지를 보내고 받고 처리하는 비동기 작업(asyncio 기반)을 지원합니다.The new API also offers support for asynchronous operations (based on asyncio) for sending, receiving and handling messages.

레거시 HTTP 기반 작업에 대한 문서는 레거시 API의 HTTP 기반 작업 사용을 참조하세요.For documentation on the legacy HTTP-based operations please see Using HTTP-based operations of the legacy API.

필수 조건Prerequisites

설치Installation

pip install azure-servicebus

Azure Service Bus에 연결Connect to Azure Service Bus

자격 증명 가져오기Get credentials

아래 Azure CLI 조각을 사용하여 Service Bus 연결 문자열로 환경 변수를 채웁니다(Azure Portal에서도 이 값을 찾을 수 있습니다).Use the Azure CLI snippet below to populate an environment variable with the Service Bus connection string (you can also find this value in the Azure portal). 조각은 Bash 셸에 대해 서식이 지정됩니다.The snippet is formatted for the Bash shell.

RES_GROUP=<resource-group-name>
NAMESPACE=<servicebus-namespace>

export SB_CONN_STR=$(az servicebus namespace authorization-rule keys list \
 --resource-group $RES_GROUP \
 --namespace-name $NAMESPACE \
 --name RootManageSharedAccessKey \
 --query primaryConnectionString \
 --output tsv)

클라이언트 만들기Create client

SB_CONN_STR 환경 변수를 채우면 ServiceBusClient를 만들 수 있습니다.Once you've populated the SB_CONN_STR environment variable, you can create the ServiceBusClient.

import os
from azure.servicebus import ServiceBusClient

connection_str = os.environ['SB_CONN_STR']

sb_client = ServiceBusClient.from_connection_string(connection_str)

비동기 작업을 사용하려는 경우 azure.servicebus.aio 네임스페이스를 사용합니다.If you wish to use asynchronous operations, please use the azure.servicebus.aio namespace.

import os
from azure.servicebus.aio import ServiceBusClient

connection_str = os.environ['SB_CONN_STR']

sb_client = ServiceBusClient.from_connection_string(connection_str)

Service Bus 큐Service Bus queues

Service Bus 큐는 푸시 스타일 배달(긴 폴링 사용)을 사용하는 고급 메시징 기능이 필요한 시나리오(대규모 메시지, 메시지 순서 지정, 단일 작업 파괴적 읽기, 예정된 배달)에 유용할 수 있는 Storage 큐의 대안입니다.Service Bus queues are an alternative to Storage queues that might be useful in scenarios where more advanced messaging features are needed (larger message sizes, message ordering, single-operation destructive reads, scheduled delivery) using push-style delivery (using long polling).

큐 만들기Create queue

이는 Service Bus 네임스페이스 내에서 새 큐를 만듭니다.This creates a new queue within the Service Bus namespace. 네임스페이스 내에 같은 이름의 큐가 이미 있으면 오류가 발생합니다.If a queue of the same name already exists within the namespace an error will be raised.

sb_client.create_queue("MyQueue")

큐 동작을 구성하는 선택적 매개 변수를 지정할 수도 있습니다.Optional parameters to configure the queue behavior can also be specified.

sb_client.create_queue(
    "MySessionQueue",
    requires_session=True  # Create a sessionful queue
    max_delivery_count=5  # Max delivery attempts per message
)

큐 클라이언트 가져오기Get a queue client

QueueClient는 다른 작업과 함께 큐와 메시지를 주고 받고 데 사용할 수 있습니다.A QueueClient can be used to send and receive messages from the queue, along with other operations.

queue_client = sb_client.get_queue("MyQueue")

메시지 보내기Sending messages

큐 클라이언트는 한 번에 하나 이상의 메시지를 보낼 수 있습니다.The queue client can send one or more messages at a time:

from azure.servicebus import Message

message = Message("Hello World")
queue_client.send(message)

message_one = Message("First")
message_two = Message("Second")
queue_client.send([message_one, message_two])

QueueClient.send를 호출할 때마다 새 서비스 연결을 만듭니다.Each call to QueueClient.send will create a new service connection. 여러 호출에 전송에 동일한 연결을 다시 사용하려면 발신자를 열 수 있습니다.To reuse the same connection for multiple send calls, you can open a sender:

message_one = Message("First")
message_two = Message("Second")

with queue_client.get_sender() as sender:
    sender.send(message_one)
    sender.send(message_two)

비동기 클라이언트를 사용하는 경우 위의 작업은 비동기 구문을 사용합니다.If you are using an asynchronous client, the above operations will use async syntax:

from azure.servicebus.aio import Message

message = Message("Hello World")
await queue_client.send(message)

message_one = Message("First")
message_two = Message("Second")
async with queue_client.get_sender() as sender:
    await sender.send(message_one)
    await sender.send(message_two)

메시지 수신Receiving messages

연속 반복기로 큐에서 메시지를 받을 수 있습니다.Messages can be received from a queue as a continuous iterator. 메시지 수신을 위한 기본 모드는 PeekLock이며 각 메시지는 큐에서 제거되도록 명시적으로 완료해야 합니다.The default mode for message receiving is PeekLock, which requires each message to be explicitly completed in order that it be removed from the queue.

messages = queue_client.get_receiver()
for message in messages:
    print(message)
    message.complete()

서비스 연결은 전체 반복기에 대해 계속 열려 있습니다.The service connection will remain open for the entirety of the iterator. 메시지 스트림을 부분적으로만 반복하는 경우 with 문에서 수신자를 실행하여 연결이 닫혔는지 확인해야 합니다.If you find yourself only partially iterating the message stream, you should run the receiver in a with statement to ensure the connection is closed:

with queue_client.get_receiver() as messages:
    for message in messages:
        print(message)
        message.complete()
        break

비동기 클라이언트를 사용하는 경우 위의 작업은 비동기 구문을 사용합니다.If you are using an asynchronous client, the above operations will use async syntax:

async with queue_client.get_receiver() as messages:
    async for message in messages:
        print(message)
        await message.complete()
        break

Service Bus 토픽 및 구독Service Bus topics and subscriptions

Service Bus 토픽 및 구독은 Service Bus 큐 위의 추상화로서 게시/구독 패턴으로 일 대 다 형태의 통신을 제공합니다.Service Bus topics and subscriptions are an abstraction on top of Service Bus queues that provide a one-to-many form of communication, in a publish/subscribe pattern. 메시지는 토픽으로 전송되어 하나 이상의 연관된 구독으로 전달되므로 많은 수의 수신자로 확장하는 데 유용합니다.Messages are sent to a topic and delivered to one or more associated subscriptions, which is useful for scaling to large numbers of recipients.

토픽 만들기Create topic

이는 Service Bus 네임스페이스 내에서 새 토픽을 만듭니다.This creates a new topic within the Service Bus namespace. 동일한 이름의 토픽이 이미 있으면 오류가 발생합니다.If a topic of the same name already exists an error will be raised.

sb_client.create_topic("MyTopic")

토픽 클라이언트 가져오기Get a topic client

다른 작업과 함께 토픽에 메시지를 보내려면 TopicClient를 사용할 수 있습니다.A TopicClient can be used to send messages to the topic, along with other operations.

topic_client = sb_client.get_topic("MyTopic")

구독 만들기Create subscription

이는 Service Bus 네임스페이스 내에서 지정된 토픽에 대한 새 구독을 만듭니다.This creates a new subscription for the specified topic within the Service Bus namespace.

sb_client.create_subscription("MyTopic", "MySubscription")

구독 클라이언트 가져오기Get a subscription client

SubscriptionClient는 다른 작업과 함께 토픽에서 메시지를 받는 데 사용할 수 있습니다.A SubscriptionClient can be used to receive messages from the topic, along with other operations.

topic_client = sb_client.get_subscription("MyTopic", "MySubscription")

v0.21.1에서 v0.50.0으로 마이그레이션Migration from v0.21.1 to v0.50.0

호환성이 손상되는 변경이 0.50.0 버전에 도입되었습니다.Major breaking changes were introduced in version 0.50.0. 원래 HTTP 기반 API는 v0.50.0에서 계속 사용할 수 있지만 이제는 새로운 네임스페이스 azure.servicebus.control_client 아래에 존재합니다.The original HTTP-based API is still available in v0.50.0 - however it now exists under a new namesapce: azure.servicebus.control_client.

업그레이드해야 합니까?Should I upgrade?

새로운 패키지(v0.50.0)는 v0.21.1 이상의 HTTP 기반 작업을 개선하지 않습니다.The new package (v0.50.0) offers no improvements in HTTP-based operations over v0.21.1. HTTP 기반 API는 이제 새 네임스페이스 아래에 있다는 점을 제외하고는 동일합니다.The HTTP-based API is identical except that it now exists under a new namespace. 따라서 HTTP 기반 작업(create_queue, delete_queue 등)만 사용하려는 경우에는 현재 업그레이드할 때 추가 이점이 없습니다.For this reason if you only wish to use HTTP-based operations (create_queue, delete_queue etc) - there will be no additional benefit in upgrading at this time.

내 코드를 새 버전으로 마이그레이션하려면 어떻게 하나요?How do I migrate my code to the new version?

v0.21.0에 대해 작성된 코드는 네임스페이스 가져오기를 변경하여 버전 0.50.0으로 가져올 수 있습니다.Code written against v0.21.0 can be ported to version 0.50.0 by simply changing the import namespace:

# from azure.servicebus import ServiceBusService  <- This will now raise an ImportError
from azure.servicebus.control_client import ServiceBusService

key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal
key_value = '' # SharedAccessKey from Azure portal
sbs = ServiceBusService(service_namespace,
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

기존 API의 HTTP 기반 작업 사용하기Using HTTP-based operations of the legacy API

다음 문서에서는 기존 API에 대해 설명하고 있으며 추가 변경 없이 기존 코드를 v0.50.0으로 가져오려는 사용자를 위한 것입니다.The following documentation describes the legacy API and should be used for those wishing to port existing code to v0.50.0 without making any additional changes. v0.21.1 사용자도 이 참조 지침을 사용할 수 있습니다.This reference can also be used as guidance by those using v0.21.1. 새 코드 작성자들은 위에서 설명한 새로운 API를 사용하는 것이 좋습니다.For those writing new code, we recommend using the new API described above.

Service Bus 큐Service Bus queues

공유 액세스 서명(SAS) 인증Shared Access Signature (SAS) authentication

공유 액세스 서명 인증을 사용하려면 다음을 사용하여 Service Bus 서비스를 만듭니다.To use Shared Access Signature authentication, create the service bus service with:

from azure.servicebus.control_client import ServiceBusService

key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal
key_value = '' # SharedAccessKey from Azure portal
sbs = ServiceBusService(service_namespace,
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

ACS(Access Control Service) 인증Access Control Service (ACS) authentication

ACS는 새 Service Bus 네임스페이스에서 지원되지 않습니다.ACS is not supported on new Service Bus namespaces. SAS 인증으로 애플리케이션을 마이그레이션 하는 것이 좋습니다.We recommend migrating applications to SAS authentication. 이전 Service Bus 네임스페이스 내에서 ACS 인증을 사용하려면 다음을 사용하여 ServiceBusService를 만듭니다.To use ACS authentication within an older Service Bus namesapce, create the ServiceBusService with:

from azure.servicebus.control_client import ServiceBusService

account_key = '' # DEFAULT KEY from Azure portal
issuer = 'owner' # DEFAULT ISSUER from Azure portal
sbs = ServiceBusService(service_namespace,
                        account_key=account_key,
                        issuer=issuer)

메시지 송수신Sending and receiving messages

create_queue 메서드를 사용하여 큐가 존재하는지 확인할 수 있습니다.The create_queue method can be used to ensure a queue exists:

sbs.create_queue('taskqueue')

send_queue_message 메서드를 호출하여 큐에 메시지를 삽입할 수 있습니다.The send_queue_message method can then be called to insert the message into the queue:

from azure.servicebus.control_client import Message

msg = Message('Hello World!')
sbs.send_queue_message('taskqueue', msg)

send_queue_message_batch 메서드를 호출하여 여러 개의 메시지를 한 번에 보낼 수 있습니다.The send_queue_message_batch method can then be called to send several messages at once:

from azure.servicebus.control_client import Message

msg1 = Message('Hello World!')
msg2 = Message('Hello World again!')
sbs.send_queue_message_batch('taskqueue', [msg1, msg2])

receive_queue_message 메서드를 호출하여 메시지를 큐에서 제거할 수 있습니다.It is then possible to call the receive_queue_message method to dequeue the message.

msg = sbs.receive_queue_message('taskqueue')

Service Bus 토픽Service Bus topics

create_topic 메서드를 사용하여 서버 쪽 항목을 만들 수 있습니다.The create_topic method can be used to create a server-side topic:

sbs.create_topic('taskdiscussion')

send_topic_message 메서드를 사용하여 항목에 메시지를 보낼 수 있습니다.The send_topic_message method can be used to send a message to a topic:

from azure.servicebus.control_client import Message

msg = Message(b'Hello World!')
sbs.send_topic_message('taskdiscussion', msg)

send_topic_message_batch 메서드를 사용하여 여러 개의 메시지를 한 번에 보낼 수 있습니다.The send_topic_message_batch method can be used to send several messages at once:

from azure.servicebus.control_client import Message

msg1 = Message(b'Hello World!')
msg2 = Message(b'Hello World again!')
sbs.send_topic_message_batch('taskdiscussion', [msg1, msg2])

Python 3에서 문자열 메시지는 utf-8로 인코딩되고 Python 2에서 인코딩을 직접 관리해야 한다는 점을 고려하세요.Please consider that in Python 3 a str message will be utf-8 encoded and you should have to manage your encoding yourself in Python 2.

클라이언트가 구독을 만들고 create_subscription 메서드 및 receive_subscription_message 메서드를 호출하여 메시지를 사용하기 시작할 수 있습니다.A client can then create a subscription and start consuming messages by calling the create_subscription method followed by the receive_subscription_message method. 구독을 만들기 전에 전송된 모든 메시지는 수신되지 않습니다.Please note that any messages sent before the subscription is created will not be received.

from azure.servicebus.control_client import Message

sbs.create_subscription('taskdiscussion', 'client1')
msg = Message('Hello World!')
sbs.send_topic_message('taskdiscussion', msg)
msg = sbs.receive_subscription_message('taskdiscussion', 'client1')

이벤트 허브Event Hub

Event Hubs를 통해 다양한 디바이스 및 서비스 집합에서 높은 처리량으로 이벤트 스트림을 수집할 수 있습니다.Event Hubs enable the collection of event streams at high throughput, from a diverse set of devices and services.

create_event_hub 메서드를 사용하여 Event Hub를 만들 수 있습니다.The create_event_hub method can be used to create an event hub:

sbs.create_event_hub('myhub')

이벤트를 보내려면:To send an event:

sbs.send_event('myhub', '{ "DeviceId":"dev-01", "Temperature":"37.0" }')

이벤트 내용은 여러 메시지를 포함하는 이벤트 메시지 또는 JSON 인코딩 문자열입니다.The event content is the event message or JSON-encoded string that contains multiple messages.

고급 기능Advanced features

Broker 속성 및 사용자 속성Broker properties and user properties

이 섹션에서는 여기에 정의된 Broker 및 사용자 속성을 사용하는 방법을 설명합니다.This section describes how to use Broker and User properties defined here:

sent_msg = Message(b'This is the third message',
                   broker_properties={'Label': 'M3'},
                   custom_properties={'Priority': 'Medium',
                                      'Customer': 'ABC'}
            )

날짜/시간, int, 부동 또는 부울 값을 사용할 수 있습니다.You can use datetime, int, float or boolean

props = {'hello': 'world',
         'number': 42,
         'active': True,
         'deceased': False,
         'large': 8555111000,
         'floating': 3.14,
         'dob': datetime(2011, 12, 14),
         'double_quote_message': 'This "should" work fine',
         'quote_message': "This 'should' work fine"}
sent_msg = Message(b'message with properties', custom_properties=props)

이 라이브러리의 이전 버전과의 호환성을 위해 broker_properties를 JSON 문자열로 정의할 수도 있습니다.For compatibility reason with old version of this library, broker_properties could also be defined as a JSON string. 이 경우에 유효한 JSON 문자열을 작성해야 합니다. RestAPI에 보내기 전에 Python에서 검사하지 않습니다.If this situation, you're responsible to write a valid JSON string, no check will be made by Python before sending to the RestAPI.

broker_properties = '{"ForcePersistence": false, "Label": "My label"}'
sent_msg = Message(b'receive message',
                   broker_properties = broker_properties
)

다음 단계Next Steps