Exemplo n.º 1
0
async def renew_lock_on_message_received_from_non_sessionful_entity():
    servicebus_client = ServiceBusClient.from_connection_string(
        conn_str=CONNECTION_STR)

    async with servicebus_client:
        async with servicebus_client.get_queue_sender(
                queue_name=QUEUE_NAME) as sender:
            msgs_to_send = [
                ServiceBusMessage("session message: {}".format(i))
                for i in range(10)
            ]
            await sender.send_messages(msgs_to_send)
            print('Send messages to non-sessionful queue.')

        # Can also be called via "with AutoLockRenewer() as renewer" to automate shutdown.
        renewer = AutoLockRenewer()

        async with servicebus_client.get_queue_receiver(
                queue_name=QUEUE_NAME, prefetch_count=10) as receiver:
            received_msgs = await receiver.receive_messages(
                max_message_count=10, max_wait_time=5)

            for msg in received_msgs:
                # automatically renew the lock on each message for 100 seconds
                renewer.register(receiver, msg, max_lock_renewal_duration=100)
            print('Register messages into AutoLockRenewer done.')

            await asyncio.sleep(
                100
            )  # message handling for long period (E.g. application logic)

            for msg in received_msgs:
                await receiver.complete_message(msg)
            print('Complete messages.')

        await renewer.close()
Exemplo n.º 2
0
import io
import json
from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://ppsoboi.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0xbO5stvtfKiGpx/qf0578e343HWNDlJXshjqOQYs2I="
QUEUE_NAME = "data-queue"

if __name__ == '__main__':
    with io.open('jobs.json', encoding='utf-8') as json_file:
        jobs_json = json.load(json_file)

    servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

    with servicebus_client:
        sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)

        with sender:
            for i, job_json in enumerate(jobs_json):
                print(f'sending message {i}...')
                message = ServiceBusMessage(json.dumps(job_json))
                sender.send_messages(message)
Exemplo n.º 3
0
async def send_single_message(sender):
    message = ServiceBusMessage("Single Message")
    await sender.send_messages(message)
def test_amqp_message():
    sb_message = ServiceBusMessage(body=None)
    assert sb_message.body_type == AmqpMessageBodyType.VALUE
    assert not sb_message.body

    amqp_annotated_message = AmqpAnnotatedMessage(data_body=b"data")
    assert amqp_annotated_message.body_type == AmqpMessageBodyType.DATA
    body = [data for data in amqp_annotated_message.body]
    assert len(body) == 1
    assert body[0] == b"data"

    amqp_annotated_message = AmqpAnnotatedMessage(
        value_body={b"key": b"value"})
    assert amqp_annotated_message.body_type == AmqpMessageBodyType.VALUE
    assert amqp_annotated_message.body == {b"key": b"value"}

    amqp_annotated_message = AmqpAnnotatedMessage(sequence_body=[1, 2, 3])
    body = [sequence for sequence in amqp_annotated_message.body]
    assert amqp_annotated_message.body_type == AmqpMessageBodyType.SEQUENCE
    assert len(body) == 1
    assert body[0] == [1, 2, 3]

    amqp_annotated_message = AmqpAnnotatedMessage(
        value_body=None,
        header=AmqpMessageHeader(priority=1,
                                 delivery_count=1,
                                 time_to_live=1,
                                 first_acquirer=True,
                                 durable=True),
        properties=AmqpMessageProperties(message_id='id',
                                         user_id='id',
                                         to='to',
                                         subject='sub',
                                         correlation_id='cid',
                                         content_type='ctype',
                                         content_encoding='cencoding',
                                         creation_time=1,
                                         absolute_expiry_time=1,
                                         group_id='id',
                                         group_sequence=1,
                                         reply_to_group_id='id'),
        footer={"key": "value"},
        delivery_annotations={"key": "value"},
        annotations={"key": "value"},
        application_properties={"key": "value"})

    assert amqp_annotated_message.body_type == AmqpMessageBodyType.VALUE
    assert amqp_annotated_message.header.priority == 1
    assert amqp_annotated_message.header.delivery_count == 1
    assert amqp_annotated_message.header.time_to_live == 1
    assert amqp_annotated_message.header.first_acquirer
    assert amqp_annotated_message.header.durable

    assert amqp_annotated_message.footer == {"key": "value"}
    assert amqp_annotated_message.delivery_annotations == {"key": "value"}
    assert amqp_annotated_message.annotations == {"key": "value"}
    assert amqp_annotated_message.application_properties == {"key": "value"}

    assert amqp_annotated_message.properties.message_id == 'id'
    assert amqp_annotated_message.properties.user_id == 'id'
    assert amqp_annotated_message.properties.to == 'to'
    assert amqp_annotated_message.properties.subject == 'sub'
    assert amqp_annotated_message.properties.correlation_id == 'cid'
    assert amqp_annotated_message.properties.content_type == 'ctype'
    assert amqp_annotated_message.properties.content_encoding == 'cencoding'
    assert amqp_annotated_message.properties.creation_time == 1
    assert amqp_annotated_message.properties.absolute_expiry_time == 1
    assert amqp_annotated_message.properties.group_id == 'id'
    assert amqp_annotated_message.properties.group_sequence == 1
    assert amqp_annotated_message.properties.reply_to_group_id == 'id'

    amqp_annotated_message = AmqpAnnotatedMessage(
        value_body=None,
        header={
            "priority": 1,
            "delivery_count": 1,
            "time_to_live": 1,
            "first_acquirer": True,
            "durable": True
        },
        properties={
            "message_id": "id",
            "user_id": "id",
            "to": "to",
            "subject": "sub",
            "correlation_id": "cid",
            "content_type": "ctype",
            "content_encoding": "cencoding",
            "creation_time": 1,
            "absolute_expiry_time": 1,
            "group_id": "id",
            "group_sequence": 1,
            "reply_to_group_id": "id"
        },
        footer={"key": "value"},
        delivery_annotations={"key": "value"},
        annotations={"key": "value"},
        application_properties={"key": "value"})

    assert amqp_annotated_message.body_type == AmqpMessageBodyType.VALUE
    assert amqp_annotated_message.header.priority == 1
    assert amqp_annotated_message.header.delivery_count == 1
    assert amqp_annotated_message.header.time_to_live == 1
    assert amqp_annotated_message.header.first_acquirer
    assert amqp_annotated_message.header.durable

    assert amqp_annotated_message.footer == {"key": "value"}
    assert amqp_annotated_message.delivery_annotations == {"key": "value"}
    assert amqp_annotated_message.annotations == {"key": "value"}
    assert amqp_annotated_message.application_properties == {"key": "value"}

    assert amqp_annotated_message.properties.message_id == 'id'
    assert amqp_annotated_message.properties.user_id == 'id'
    assert amqp_annotated_message.properties.to == 'to'
    assert amqp_annotated_message.properties.subject == 'sub'
    assert amqp_annotated_message.properties.correlation_id == 'cid'
    assert amqp_annotated_message.properties.content_type == 'ctype'
    assert amqp_annotated_message.properties.content_encoding == 'cencoding'
    assert amqp_annotated_message.properties.creation_time == 1
    assert amqp_annotated_message.properties.absolute_expiry_time == 1
    assert amqp_annotated_message.properties.group_id == 'id'
    assert amqp_annotated_message.properties.group_sequence == 1
    assert amqp_annotated_message.properties.reply_to_group_id == 'id'
def example_send_and_receive_sync():
    servicebus_sender = example_create_servicebus_sender_sync()
    servicebus_receiver = example_create_servicebus_receiver_sync()

    from azure.servicebus import ServiceBusMessage
    # [START send_sync]
    with servicebus_sender:
        message = ServiceBusMessage("Hello World")
        servicebus_sender.send_messages(message)
        # [END send_sync]
        servicebus_sender.send_messages([ServiceBusMessage("Hello World")] * 5)

    # [START create_batch_sync]
    with servicebus_sender:
        batch_message = servicebus_sender.create_message_batch()
        batch_message.add_message(
            ServiceBusMessage("Single message inside batch"))
    # [END create_batch_sync]

    # [START send_complex_message]
    message = ServiceBusMessage("Hello World!!",
                                session_id="MySessionID",
                                partition_key="UsingSpecificPartition",
                                user_properties={'data': 'custom_data'},
                                time_to_live=datetime.timedelta(seconds=30),
                                label='MyLabel')
    # [END send_complex_message]

    # [START peek_messages_sync]
    with servicebus_receiver:
        messages = servicebus_receiver.peek_messages()
        for message in messages:
            print(str(message))
    # [END peek_messages_sync]

    # [START auto_lock_renew_message_sync]
    from azure.servicebus import AutoLockRenewer
    lock_renewal = AutoLockRenewer(max_workers=4)
    with servicebus_receiver:
        for message in servicebus_receiver:
            # Auto renew message for 1 minute.
            lock_renewal.register(servicebus_receiver,
                                  message,
                                  max_lock_renewal_duration=60)
            process_message(message)
            servicebus_receiver.complete_message(message)
            # [END auto_lock_renew_message_sync]
            break

    # [START receive_sync]
    with servicebus_receiver:
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            print(str(message))
            servicebus_receiver.complete_message(message)
    # [END receive_sync]

    # [START receive_complex_message]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            print("Receiving: {}".format(message))
            print("Time to live: {}".format(message.time_to_live))
            print("Sequence number: {}".format(message.sequence_number))
            print("Enqueued Sequence numger: {}".format(
                message.enqueued_sequence_number))
            print("Partition Key: {}".format(message.partition_key))
            print("Application Properties: {}".format(
                message.application_properties))
            print("Delivery count: {}".format(message.delivery_count))
            print("Message ID: {}".format(message.message_id))
            print("Locked until: {}".format(message.locked_until_utc))
            print("Lock Token: {}".format(message.lock_token))
            print("Enqueued time: {}".format(message.enqueued_time_utc))
        # [END receive_complex_message]

        # [START abandon_message_sync]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            servicebus_receiver.abandon_message(message)
        # [END abandon_message_sync]

        # [START complete_message_sync]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            servicebus_receiver.complete_message(message)
        # [END complete_message_sync]

        # [START defer_message_sync]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            servicebus_receiver.defer_message(message)
        # [END defer_message_sync]

        # [START dead_letter_message_sync]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            servicebus_receiver.dead_letter_message(message)
        # [END dead_letter_message_sync]

        # [START renew_message_lock_sync]
        messages = servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            servicebus_receiver.renew_message_lock(message)
        # [END renew_message_lock_sync]

    # [START receive_forever]
    with servicebus_receiver:
        for message in servicebus_receiver.get_streaming_message_iter():
            print(str(message))
            servicebus_receiver.complete_message(message)
            # [END receive_forever]
            break
Exemplo n.º 6
0
async def invoke_porter_action(msg_body: dict, sb_client: ServiceBusClient,
                               message_logger_adapter: logging.LoggerAdapter,
                               config: dict) -> bool:
    """
    Handle resource message by invoking specified porter action (i.e. install, uninstall)
    """
    installation_id = get_installation_id(msg_body)
    action = msg_body["action"]
    message_logger_adapter.info(
        f"{installation_id}: {action} action starting...")
    sb_sender = sb_client.get_queue_sender(
        queue_name=config["deployment_status_queue"])

    # If the action is install/upgrade, post message on sb queue to start a deployment job
    if action == "install" or action == "upgrade":
        resource_request_message = service_bus_message_generator(
            msg_body, strings.RESOURCE_STATUS_DEPLOYING,
            "Deployment job starting")
        await sb_sender.send_messages(
            ServiceBusMessage(body=resource_request_message,
                              correlation_id=msg_body["id"]))

    # Build and run porter command (flagging if its a built-in action or custom so we can adapt porter command appropriately)
    is_custom_action = action not in ["install", "upgrade", "uninstall"]
    porter_command = await build_porter_command(config, message_logger_adapter,
                                                msg_body, is_custom_action)
    returncode, _, err = await run_porter(porter_command,
                                          message_logger_adapter, config)

    # Handle command output
    if returncode != 0:
        error_message = "Error context message = " + " ".join(
            err.split('\n')) + " ; Command executed: ".join(porter_command)
        resource_request_message = service_bus_message_generator(
            msg_body, statuses.failed_status_string_for[action], error_message)

        # Post message on sb queue to notify receivers of action failure
        await sb_sender.send_messages(
            ServiceBusMessage(body=resource_request_message,
                              correlation_id=msg_body["id"]))
        message_logger_adapter.info(
            f"{installation_id}: Porter action failed with error = {error_message}"
        )
        return False

    else:
        # Get the outputs
        # TODO: decide if this should "fail" the deployment
        _, outputs = await get_porter_outputs(msg_body, message_logger_adapter,
                                              config)

        success_message = f"{action} action completed successfully."
        resource_request_message = service_bus_message_generator(
            msg_body, statuses.pass_status_string_for[action], success_message,
            outputs)

        await sb_sender.send_messages(
            ServiceBusMessage(body=resource_request_message,
                              correlation_id=msg_body["id"]))
        message_logger_adapter.info(f"{installation_id}: {success_message}")
        return True
Exemplo n.º 7
0
 def send_list_messages(sender: ServiceBusSender, messages: List[str]):
     list_messages = [ServiceBusMessage(message) for message in messages]
     sender.send_messages(list_messages)  # type: ignore[arg-type]
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)

# azure monitor trace exporter to send telemetry to appinsights
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
span_processor = BatchSpanProcessor(
    AzureMonitorTraceExporter.from_connection_string(
        os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
trace.get_tracer_provider().add_span_processor(span_processor)

# Example with Servicebus SDKs
from azure.servicebus import ServiceBusClient, ServiceBusMessage

connstr = os.environ['SERVICE_BUS_CONN_STR']
queue_name = os.environ['SERVICE_BUS_QUEUE_NAME']

with tracer.start_as_current_span(name="MyApplication"):
    with ServiceBusClient.from_connection_string(connstr) as client:
        with client.get_queue_sender(queue_name) as sender:
            # Sending a single message
            single_message = ServiceBusMessage("Single message")
            sender.send_messages(single_message)

            # Sending a list of messages
            messages = [
                ServiceBusMessage("First message"),
                ServiceBusMessage("Second message")
            ]
            sender.send_messages(messages)
Exemplo n.º 9
0
def send_single_message(sender):
    message = ServiceBusMessage(json.dumps(json_object))
    sender.send_messages(message)
    print("Sent a single message")
Exemplo n.º 10
0
async def send_message():
    async with ServiceBusClient(FULLY_QUALIFIED_NAMESPACE,
                                credential) as client:
        async with client.get_queue_sender(QUEUE_NAME) as sender:
            await sender.send_messages([ServiceBusMessage("hello")])
Exemplo n.º 11
0
def send_message(client, queue_name):
    queue_client = client.get_queue(queue_name)
    msg = ServiceBusMessage(b'Test')
    queue_client.send(msg)
    print('ServiceBusMessage sent')
Exemplo n.º 12
0
def send_single_message(sender):
    #generate message
    message = ServiceBusMessage("Single Message")
    #send message
    sender.send_messages(message)
Exemplo n.º 13
0
def send_a_list_of_messages(sender):
    #generate messages
    messages = [ServiceBusMessage("Message in list") for _ in range(10)]
    #send messages
    sender.send_messages(messages)
Exemplo n.º 14
0
"""

# pylint: disable=C0111

import os
from azure.servicebus import ServiceBusMessage, ServiceBusClient

CONNECTION_STR = os.environ['SERVICE_BUS_CONNECTION_STR']
QUEUE_NAME = os.environ["SERVICE_BUS_QUEUE_NAME"]

servicebus_client = ServiceBusClient.from_connection_string(
    conn_str=CONNECTION_STR)

with servicebus_client:
    sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
    messages = [ServiceBusMessage("Message to be deferred") for _ in range(10)]
    with sender:
        sender.send_messages(messages)

    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME)
    with receiver:
        received_msgs = receiver.receive_messages(max_message_count=10,
                                                  max_wait_time=5)
        deferred_sequenced_numbers = []
        for msg in received_msgs:
            print("Deferring msg: {}".format(str(msg)))
            deferred_sequenced_numbers.append(msg.sequence_number)
            msg.defer()

        if deferred_sequenced_numbers:
            received_deferred_msg = receiver.receive_deferred_messages(
Exemplo n.º 15
0
def send_message_to_queue(sender, not_id):
    # create a Service Bus message
    message = ServiceBusMessage(str(not_id))
    # send the message to the queue
    sender.send_messages(message)
# pylint: disable=C0111

import os
from azure.servicebus import ServiceBusClient, ServiceBusMessage, SubQueue

CONNECTION_STR = os.environ['SERVICE_BUS_CONNECTION_STR']
QUEUE_NAME = os.environ["SERVICE_BUS_QUEUE_NAME"]

servicebus_client = ServiceBusClient.from_connection_string(
    conn_str=CONNECTION_STR)

with servicebus_client:
    sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
    messages = [
        ServiceBusMessage("Message to be deadlettered") for _ in range(10)
    ]
    with sender:
        sender.send_messages(messages)

    print('dead lettering messages')
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME)
    with receiver:
        received_msgs = receiver.receive_messages(max_message_count=10,
                                                  max_wait_time=5)
        for msg in received_msgs:
            print(str(msg))
            msg.dead_letter()

    print('receiving deadlettered messages')
    dlq_receiver = servicebus_client.get_queue_receiver(
tracer = trace.get_tracer(__name__)

# azure monitor trace exporter to send telemetry to appinsights
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

# Simple console exporter
exporter = ConsoleSpanExporter()
span_processor = SimpleSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

# Example with Servicebus SDKs
from azure.servicebus import ServiceBusClient, ServiceBusMessage

connstr = os.environ['SERVICE_BUS_CONN_STR']
queue_name = os.environ['SERVICE_BUS_QUEUE_NAME']

with tracer.start_as_current_span(name="MyApplication2"):
    with ServiceBusClient.from_connection_string(connstr) as client:
        with client.get_queue_sender("new_queue") as sender:
            #Sending a single message
            single_message = ServiceBusMessage("Single message")
            sender.send_messages(single_message)
        # continually receives new messages until it doesn't receive any new messages for 5 (max_wait_time) seconds.
        with client.get_queue_receiver(queue_name="new_queue",
                                       max_wait_time=5) as receiver:
            # Receive all messages
            for msg in receiver:
                print("Received: " + str(msg))
                receiver.complete_message(msg)
Exemplo n.º 18
0
def send_single_message(sender):
    message = ServiceBusMessage("Single session message",
                                session_id=SESSION_ID)
    sender.send_messages(message)
Exemplo n.º 19
0
async def send_deployment_message(content, correlation_id, session_id, action):
    resource_request_message = ServiceBusMessage(body=content, correlation_id=correlation_id, session_id=session_id)
    logging.info(f"Sending resource request message with correlation ID {resource_request_message.correlation_id}, action: {action}")
    await _send_message(resource_request_message, config.SERVICE_BUS_RESOURCE_REQUEST_QUEUE)
Exemplo n.º 20
0
def send_a_list_of_messages(sender):
    messages = [
        ServiceBusMessage("Session Message in list", session_id=SESSION_ID)
        for _ in range(10)
    ]
    sender.send_messages(messages)
Exemplo n.º 21
0
 def send_batch_message(sender: ServiceBusSender, messages: List[str]):
     batch_message = sender.create_message_batch()
     for message in messages:
         batch_message.add_message(ServiceBusMessage(message))
     sender.send_messages(batch_message)
Exemplo n.º 22
0
def schedule_single_message(sender):
    message = ServiceBusMessage("Message to be scheduled")
    scheduled_time_utc = datetime.datetime.utcnow() + datetime.timedelta(
        seconds=30)
    sequence_number = sender.schedule_messages(message, scheduled_time_utc)
    return sequence_number
    async def test_topic_by_servicebus_client_receive_batch_with_deadletter(
            self, servicebus_namespace_connection_string, servicebus_topic,
            servicebus_subscription, **kwargs):

        async with ServiceBusClient.from_connection_string(
                servicebus_namespace_connection_string,
                logging_enable=False) as sb_client:

            async with sb_client.get_subscription_receiver(
                    topic_name=servicebus_topic.name,
                    subscription_name=servicebus_subscription.name,
                    max_wait_time=5,
                    receive_mode=ReceiveMode.PeekLock,
                    prefetch_count=10) as receiver:

                async with sb_client.get_topic_sender(
                        servicebus_topic.name) as sender:
                    for i in range(10):
                        message = ServiceBusMessage(
                            "Dead lettered message no. {}".format(i))
                        await sender.send_messages(message)

                count = 0
                messages = await receiver.receive_messages()
                while messages:
                    for message in messages:
                        print_message(_logger, message)
                        count += 1
                        await message.dead_letter(
                            reason="Testing reason",
                            error_description="Testing description")
                    messages = await receiver.receive_messages()

                assert count == 10

            async with sb_client.get_subscription_receiver(
                    topic_name=servicebus_topic.name,
                    subscription_name=servicebus_subscription.name,
                    max_wait_time=5,
                    receive_mode=ReceiveMode.PeekLock) as receiver:
                count = 0
                async for message in receiver:
                    print_message(_logger, message)
                    await message.complete()
                    count += 1
            assert count == 0

            async with sb_client.get_subscription_receiver(
                    topic_name=servicebus_topic.name,
                    subscription_name=servicebus_subscription.name,
                    sub_queue=SubQueue.DeadLetter,
                    max_wait_time=5,
                    receive_mode=ReceiveMode.PeekLock) as dl_receiver:
                count = 0
                async for message in dl_receiver:
                    await message.complete()
                    count += 1
                    assert message.dead_letter_reason == 'Testing reason'
                    assert message.dead_letter_error_description == 'Testing description'
                    assert message.properties[
                        b'DeadLetterReason'] == b'Testing reason'
                    assert message.properties[
                        b'DeadLetterErrorDescription'] == b'Testing description'
                assert count == 10
Exemplo n.º 24
0
async def example_send_and_receive_async():
    servicebus_sender = await example_create_servicebus_sender_async()
    servicebus_receiver = await example_create_servicebus_receiver_async()

    from azure.servicebus import ServiceBusMessage
    # [START send_async]
    async with servicebus_sender:
        message = ServiceBusMessage("Hello World")
        await servicebus_sender.send_messages(message)
        # [END send_async]
        await servicebus_sender.send_messages(
            [ServiceBusMessage("Hello World")] * 5)

    # [START create_batch_async]
    async with servicebus_sender:
        batch_message = await servicebus_sender.create_message_batch()
        batch_message.add_message(
            ServiceBusMessage("Single message inside batch"))
    # [END create_batch_async]

    # [START peek_messages_async]
    async with servicebus_receiver:
        messages = await servicebus_receiver.peek_messages()
        for message in messages:
            print(str(message))
    # [END peek_messages_async]

    # [START receive_async]
    async with servicebus_receiver:
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            print(str(message))
            await servicebus_receiver.complete_message(message)
    # [END receive_async]

    # [START receive_forever_async]
    async with servicebus_receiver:
        async for message in servicebus_receiver.get_streaming_message_iter():
            print(str(message))
            await servicebus_receiver.complete_message(message)
            # [END receive_forever_async]
            break

        # [START abandon_message_async]
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            await servicebus_receiver.abandon_message(message)
        # [END abandon_message_async]

        # [START complete_message_async]
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            await servicebus_receiver.complete_message(message)
        # [END complete_message_async]

        # [START defer_message_async]
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            await servicebus_receiver.defer_message(message)
        # [END defer_message_async]

        # [START dead_letter_message_async]
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            await servicebus_receiver.dead_letter_message(message)
        # [END dead_letter_message_async]

        # [START renew_message_lock_async]
        messages = await servicebus_receiver.receive_messages(max_wait_time=5)
        for message in messages:
            await servicebus_receiver.renew_message_lock(message)
        # [END renew_message_lock_async]

    # [START auto_lock_renew_message_async]
    from azure.servicebus.aio import AutoLockRenewer

    lock_renewal = AutoLockRenewer()
    async with servicebus_receiver:
        async for message in servicebus_receiver:
            lock_renewal.register(servicebus_receiver,
                                  message,
                                  max_lock_renewal_duration=60)
            await process_message(message)
            await servicebus_receiver.complete_message(message)
            # [END auto_lock_renew_message_async]
            break
    await lock_renewal.close()
def test_servicebus_message_repr():
    message = ServiceBusMessage("hello")
    assert "application_properties=None, session_id=None," in message.__repr__(
    )
    assert "content_type=None, correlation_id=None, to=None, reply_to=None, reply_to_session_id=None, subject=None, time_to_live=None, partition_key=None, scheduled_enqueue_time_utc" in message.__repr__(
    )
def create_message(label, correlation_id=None):
    return ServiceBusMessage("Rule with filter sample",
                             application_properties={"Color": label},
                             subject=label,
                             correlation_id=correlation_id)
def test_servicebus_message_time_to_live():
    message = ServiceBusMessage(body="hello")
    message.time_to_live = timedelta(seconds=30)
    assert message.time_to_live == timedelta(seconds=30)
    message.time_to_live = timedelta(days=1)
    assert message.time_to_live == timedelta(days=1)
def send_a_list_of_messages(sender):
    messages = [ServiceBusMessage("Message in list") for _ in range(100)]
    sender.send_messages(messages)
    logger.info("Sent a list of 100 messages")
Exemplo n.º 29
0
async def send_a_list_of_messages(sender):
    messages = [ServiceBusMessage("Message in list") for _ in range(10)]
    await sender.send_messages(messages)
Exemplo n.º 30
0
 async def run_async(self):
     message = ServiceBusMessage(self.data)
     await self.async_sender.send_messages(message)