def blocking_consume_direct_messages_in_loop_with_time_out(
         service: MessagingService, consumer_subscription: str,
         receive_timeout):
     try:
         topics = [TopicSubscription.of(consumer_subscription)]
         receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
             .with_subscriptions(topics).build()
         receiver.start()
         count = 0
         for count in range(100):
             try:
                 with ThreadPoolExecutor(max_workers=1) as e:
                     e.submit(
                         HowToDirectPublishMessage.direct_message_publish,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)
                 message_payload: 'InboundMessage' = receiver.receive_message(
                     receive_timeout)
                 print(
                     f"message_payload in string: {message_payload.get_payload_as_string()}, msg_count: {count}"
                 )
             except PubSubPlusClientError as exception:
                 raise exception
     finally:
         receiver.terminate()
    def consume_direct_message_published_from_rest_client(
            service: MessagingService, consumer_subscription: str):
        """To consume direct message payload with content type and content encoding using receive_message()"""
        try:
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
                .with_subscriptions(topics).build()
            receiver.start()

            with ThreadPoolExecutor(max_workers=1) as e:
                e.submit(HowToDirectPublishMessage.
                         direct_message_publish_outbound_with_all_props,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)

            message_payload: 'InboundMessage' = receiver.receive_message()

            rest_specific_fields = message_payload.get_rest_interoperability_support(
            )
            content_type = rest_specific_fields.get_http_content_type()
            content_encoding = rest_specific_fields.get_http_content_encoding()
            print(
                f"received message content type is :{content_type} \n content encoding is : {content_encoding}"
            )
        finally:
            receiver.terminate()
    def run():
        """
        :return:
        """
        service = None
        try:
            service = MessagingService.builder().from_properties(
                boot.broker_properties()).build()
            service.connect()
            print(f"Message service: {service.is_connected}")
            if service.is_connected:
                destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
                message_count = 10

                print(
                    "Execute Direct Publish - String without using back pressure"
                )
                HowToDirectMessagingHealthCheckSampler() \
                    .direct_message_publish_without_backpressure(service, destination_name,
                                                                 constants.MESSAGE_TO_SEND,
                                                                 message_count)

                buffer_capacity = 100
                print("Execute Direct Publish - String using back pressure")
                HowToDirectMessagingHealthCheckSampler() \
                    .direct_message_publish_on_backpressure_reject(service, destination_name,
                                                                   constants.MESSAGE_TO_SEND,
                                                                   buffer_capacity, message_count)
            else:
                print(
                    f'Failed to connect service with properties: {boot.broker_properties()}'
                )
        finally:
            if service:
                service.disconnect()
Exemplo n.º 4
0
    def run():
        """
        :return:
        """
        try:
            service = MessagingService.builder().from_properties(
                boot.broker_properties()).build()
            result = service.connect_async().result()
            print(f"Message service status: {result}")
            if result == 0:
                destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
                message_count = 10

                print(
                    "Execute Direct Publish - String without using back pressure"
                )
                HowToDirectMessagingHealthCheckSampler() \
                    .direct_message_publish_without_backpressure(service, destination_name,
                                                                 constants.MESSAGE_TO_SEND,
                                                                 message_count)

                buffer_capacity = 100
                print("Execute Direct Publish - String using back pressure")
                HowToDirectMessagingHealthCheckSampler() \
                    .direct_message_publish_on_backpressure_reject(service, destination_name,
                                                                   constants.MESSAGE_TO_SEND,
                                                                   buffer_capacity, message_count)
        finally:
            service.disconnect_async()
    def run():
        """
        :return:
        """
        service = None
        try:
            service = MessagingService.builder().from_properties(
                boot.broker_properties()).build()
            service.connect()
            print(f"Message service connected: {service.is_connected}")
            if service.is_connected:
                destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
                message_count = 10
                buffer_capacity = 100
                print("Execute Direct Publish - String using back pressure")
                HowToDirectPublishWithBackPressureSampler() \
                    .direct_message_publish_on_backpressure_reject(service, destination_name, constants.MESSAGE_TO_SEND,
                                                                   buffer_capacity, message_count)

                print(
                    "Execute Direct Publish - String Outbound Message with all props using back pressure"
                )
                HowToDirectPublishWithBackPressureSampler(). \
                    direct_message_publish_outbound_with_all_props_on_backpressure_on_reject(service, destination_name,
                                                                                             constants.MESSAGE_TO_SEND
                                                                                             + "_outbound based",
                                                                                             buffer_capacity,
                                                                                             message_count)

                print(
                    "Execute Direct Publish - String Outbound Message with all props using back pressure elastic"
                )
                HowToDirectPublishWithBackPressureSampler() \
                    .direct_message_publish_outbound_with_all_props_on_backpressure_elastic(service, destination_name,
                                                                                            constants.MESSAGE_TO_SEND +
                                                                                            "_outbound based",
                                                                                            message_count)

                print(
                    "Execute Direct Publish - String Outbound Message with all props using back pressure wait"
                )
                HowToDirectPublishWithBackPressureSampler() \
                    .direct_message_publish_outbound_with_all_props_on_backpressure_wait(service, destination_name,
                                                                                         constants.MESSAGE_TO_SEND
                                                                                         + str("_outbound based"),
                                                                                         buffer_capacity,
                                                                                         message_count)
            else:
                print(
                    "failed to connect service with properties: {boot.broker_properties}"
                )

        finally:
            if service:
                service.disconnect()
Exemplo n.º 6
0
 def publish_message_with_unique_service():
     try:
         service = MessagingService.builder().from_properties(
             boot.broker_properties()).build()
         service.connect_async()
         destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
         direct_publish_service = service.create_direct_message_publisher_builder(
         ).build()
         direct_publish_service.start_async()
         direct_publish_service.publish(destination=destination_name,
                                        message=constants.MESSAGE_TO_SEND)
     finally:
         service.disconnect()
         direct_publish_service.terminate(0)
    def run():
        """
            this method creates a messaging service connection and publishes the message
         """
        service = MessagingService.builder().from_properties(
            boot.broker_properties()).build()
        service.connect_async()
        destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)

        print("Execute Direct Publish - Generics Outbound Message")
        HowToDirectMessagePublishBusinessObject() \
            .direct_message_publish_outbound_business_obj(service, destination_name,
                                                          message_obj=MyData('some value'),
                                                          converter=PopoConverter())
 def consume_direct_message_byte_payload(service: MessagingService,
                                         consumer_subscription: str):
     """To consume direct message payload in bytes using receive_message()"""
     try:
         topics = [TopicSubscription.of(consumer_subscription)]
         receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
             .with_subscriptions(topics).build()
         receiver.start()
         with ThreadPoolExecutor(max_workers=1) as e:
             e.submit(HowToDirectPublishMessage.direct_message_publish,
                      messaging_service=service,
                      destination=Topic.of(consumer_subscription),
                      message=constants.MESSAGE_TO_SEND)
         message_payload = receiver.receive_message().get_payload_as_bytes()
         print(f"received message payload in bytes is : {message_payload}")
     finally:
         receiver.terminate()
Exemplo n.º 9
0
    def run():
        try:
            messaging_service = MessagingService.builder().from_properties(
                boot.broker_properties()).build()
            messaging_service.connect_async()
            destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
            buffer_capacity = 20
            message_count = 50

            HowToHandleServiceInterruptionAndFailures.notify_on_direct_publisher_failures(
                messaging_service, destination_name, constants.MESSAGE_TO_SEND,
                buffer_capacity, message_count)
            HowToHandleServiceInterruptionAndFailures.\
                notify_about_service_access_unrecoverable_interruption(messaging_service,
                                                                       destination_name, constants.MESSAGE_TO_SEND)
        finally:
            messaging_service.disconnect_async()
    def run():
        try:
            message = constants.MESSAGE_TO_SEND
            messaging_service = MessagingService.builder().from_properties(boot.broker_properties()).build()
            messaging_service.connect()
            print(f'Message service is connected? {messaging_service.is_connected}')
            topic_name = constants.TOPIC_ENDPOINT_DEFAULT
            topic = Topic.of(topic_name)

            outbound_msg = messaging_service.message_builder() \
                .with_application_message_id(constants.APPLICATION_MESSAGE_ID)

            publisher = HowToPublishPersistentMessage.create_persistent_message_publisher(messaging_service)

            HowToPublishPersistentMessage.publish_byte_message_non_blocking(publisher, topic,
                                                                            bytearray(message,
                                                                                      _sol_constants.ENCODING_TYPE))

            HowToPublishPersistentMessage.publish_string_message_non_blocking(publisher, topic, message)

            HowToPublishPersistentMessage.publish_typed_message_non_blocking(message_builder=outbound_msg,
                                                                             message_publisher=publisher,
                                                                             destination=topic,
                                                                             message=message)

            HowToPublishPersistentMessage \
                .publish_typed_message_with_extended_message_props_non_blocking(message_builder=outbound_msg,
                                                                                message_publisher=publisher,
                                                                                destination=topic,
                                                                                message=message)

            HowToPublishPersistentMessage \
                .correlate_message_on_broker_ack_with_user_context_non_blocking(message_builder=outbound_msg,
                                                                                message_publisher=publisher,
                                                                                destination=topic,
                                                                                message=message)
            HowToPublishPersistentMessage \
                .publish_byte_message_blocking_waiting_for_publisher_confirmation(messaging_service=messaging_service,
                                                                                 message_publisher=publisher,
                                                                                 destination=topic,
                                                                                 message=message,
                                                                                 time_out=2000)

        finally:
            publisher.terminate()
            messaging_service.disconnect()
    def add_listener_when_reconnection_happens(retries: int, retry_interval: int) -> 'MessagingService':
        """method adds a reconnection listener when an reconnection happens using the reconnection strategy
        Args:
            retries (int): the number of retries count
            retry_interval (int): the retry interval value

        Returns:
            the listener events
        """
        events = list()

        def on_reconnection(event_p):
            events.append(event_p)
            print("current event", events)

        try:
            destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
            message = constants.MESSAGE_TO_SEND
            number_of_message_to_send = 10

            messaging_service = MessagingService.builder().from_properties(boot.broker_properties()) \
                .with_reconnection_retry_strategy(RetryStrategy.parametrized_retry(retries, retry_interval)) \
                .add_reconnection_listener(on_reconnection).build()
            messaging_service1_status_code = messaging_service.connect_async()
            print("messaging service status code: ", messaging_service1_status_code)
            for _ in range(number_of_message_to_send):
                publish_service = messaging_service.create_direct_message_publisher_builder().build()
                publish_service.publish(destination=destination_name, message=message)

            session_force_failure_status = messaging_service.disconnect_force()

            print("session force failure status: ", session_force_failure_status)

            for _ in range(number_of_message_to_send):
                publish_service = messaging_service.create_direct_message_publisher_builder().build()
                publish_service.publish(destination=destination_name, message=message)
            messaging_service.disconnect()

        finally:
            timeout = time.time() + 60 * 1
            while True:
                if 13 in events or time.time() > timeout:
                    break
            return events  # MessagingService got list
Exemplo n.º 12
0
def publish_mesg(transaction_str):
    # Create a direct message publisher and start it
    direct_publisher = messaging_service.create_direct_message_publisher_builder().build()
    direct_publisher.set_publish_failure_listener(PublisherErrorHandling())
    direct_publisher.set_publisher_readiness_listener

    # Blocking Start thread
    direct_publisher.start()

    outbound_msg = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python") \
                .build(transaction_str)

    msgSeqNum = 1

    print("transaction details: ", str(transaction_str))

    direct_publisher.publish(destination=Topic.of(TOPIC_TST + f"/python/{msgSeqNum}"), message=outbound_msg)
    direct_publisher.terminate()
    def run():
        messaging_service = None
        try:
            reply_timeout = 10000
            topic_name = f'request_reply/pub_sub/sampler'
            topic = Topic.of(topic_name)
            topic_subscription = TopicSubscription.of(topic_name)
            messaging_service = MessagingService.builder().from_properties(SamplerBoot().broker_properties()).build()
            messaging_service.connect()

            HowToUseRequestReplyPattern.async_request_and_response(service=messaging_service,
                                                                   request_destination=topic,
                                                                   for_requests=topic_subscription,
                                                                   reply_timeout=reply_timeout)

            HowToUseRequestReplyPattern.blocking_request_and_response(service=messaging_service,
                                                                      request_destination=topic,
                                                                      for_requests=topic_subscription,
                                                                      reply_timeout=reply_timeout)
        finally:
            if messaging_service:
                messaging_service.disconnect()
    def publish_request_and_process_response_message_async(service: MessagingService, request_destination: Topic,
                                                           reply_timeout: int):
        """Mimics microservice that performs a async request
        Args:
            service: connected messaging service
            request_destination: where to send a request (it is same for requests and responses)
            reply_timeout: the reply timeout
        """
        topic = Topic.of(request_destination)
        requester: RequestReplyMessagePublisher = service.request_reply() \
            .create_request_reply_message_publisher_builder().build().start()
        try:
            ping_message = service.message_builder().build(payload='Ping',
                                                           additional_message_properties={SEQUENCE_NUMBER: 123})

            publish_request_async = requester.publish(request_message=ping_message,
                                                      request_destination=topic,
                                                      reply_timeout=reply_timeout)
            # we can get the reply from the future
            print(publish_request_async.result())
        finally:
            requester.terminate()
    def consume_direct_detailed_message(service: MessagingService,
                                        consumer_subscription: str):
        try:
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
                .with_subscriptions(topics).build()
            receiver.start()

            with ThreadPoolExecutor(max_workers=1) as e:
                e.submit(HowToDirectPublishMessage.
                         direct_message_publish_outbound_with_all_props,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)

            message_payload: 'InboundMessage' = receiver.receive_message()
            expiration = message_payload.get_expiration()
            print(
                f"received message payload is :{message_payload.get_payload_as_string()} "
                f"\n expiration is : {expiration}")
        finally:
            receiver.terminate()
    def run():
        try:
            messaging_service = MessagingService.builder().from_properties(boot.broker_properties()).build()
            messaging_service.connect()
            destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)
            buffer_capacity = 20
            message_count = 50
            queue_name = 'Q/test/pub_sub'
            durable_exclusive_queue = Queue.durable_exclusive_queue(queue_name)

            HowToHandleServiceInterruptionAndFailures.notify_on_direct_publisher_failures(messaging_service,
                                                                                          destination_name,
                                                                                          constants.MESSAGE_TO_SEND,
                                                                                          buffer_capacity,
                                                                                          message_count)
            HowToHandleServiceInterruptionAndFailures. \
                notify_about_service_access_unrecoverable_interruption(messaging_service,
                                                                       destination_name, constants.MESSAGE_TO_SEND)

            HowToHandleServiceInterruptionAndFailures. \
                notify_about_persistent_receiver_termination(messaging_service, queue=durable_exclusive_queue)

        finally:
            messaging_service.disconnect()
Exemplo n.º 17
0
from solace.messaging.receiver.persistent_message_receiver import PersistentMessageReceiver
from solace.messaging.resources.queue import Queue
from solace.messaging.resources.topic import Topic
from solace.messaging.resources.topic_subscription import TopicSubscription
from howtos.pubsub.how_to_consume_persistent_message import HowToConsumeMessageExclusiveVsSharedMode
from howtos.pubsub.how_to_publish_persistent_message import HowToPublishPersistentMessage
from howtos.sampler_boot import SolaceConstants, SamplerBoot, BasicTestMessageHandler
from howtos.sampler_master import SamplerMaster

X = TypeVar('X')
constants = SolaceConstants
boot = SamplerBoot()
lock = threading.Lock()

topic_name = constants.TOPIC_ENDPOINT_DEFAULT
topic = Topic.of(topic_name)


class HowToConsumePersistentMessageWithAutoAcknowledgement:
    """class contains methods to consume message with auto acknowledgement"""

    @staticmethod
    def consume_full_message_and_do_ack(service: MessagingService, queue_to_consume: Queue, publisher, message):
        receiver: PersistentMessageReceiver = service.create_persistent_message_receiver_builder() \
            .with_message_auto_acknowledgement().build(queue_to_consume)
        receiver.start()
        print(f'PERSISTENT receiver started... Listening to Queue [{queue_to_consume.get_name()}]')
        receiver.add_subscription(TopicSubscription.of(topic_name))

        HowToPublishPersistentMessage.publish_string_message_non_blocking(publisher, topic, message)
Exemplo n.º 18
0
    if direct_receiver.is_running():
        print("Connected and Subscribed! Ready to publish\n")
    try:
        while not SHUTDOWN:
            msgSeqNum += 1
            # Check https://docs.solace.com/API-Developer-Online-Ref-Documentation/python/source/rst/solace.messaging.config.solace_properties.html for additional message properties
            # Note: additional properties override what is set by the message_builder
            additional_properties = {
                APPLICATION_MESSAGE_ID: f'sample_id {msgSeqNum}'
            }
            # Creating a dynamic outbound message
            outbound_message = message_builder.build(
                f'{message_body} --> {msgSeqNum}',
                additional_message_properties=additional_properties)
            # Direct publish the message
            direct_publisher.publish(destination=Topic.of(
                TOPIC_PREFIX + f"/python/hello/{unique_name}/{msgSeqNum}"),
                                     message=outbound_message)
            # sleep are not necessary when dealing with the default back pressure elastic
            time.sleep(5)
    except KeyboardInterrupt:
        print('\nDisconnecting Messaging Service')
    except PubSubPlusClientError as exception:
        print(f'Received a PubSubPlusClientException: {exception}')
finally:
    print('Terminating Publisher and Receiver')
    direct_publisher.terminate()
    direct_receiver.terminate()
    print('Disconnecting Messaging Service')
    messaging_service.disconnect()
                .build(message_body)
try:
    print(f"Subscribed to: {topics}")
    # Build a Receiver
    direct_receiver = messaging_service.create_direct_message_receiver_builder(
    ).with_subscriptions(topics_sub).build()
    direct_receiver.start()
    # Callback for received messages
    direct_receiver.receive_async(MessageHandlerImpl())
    if direct_receiver.is_running():
        print("Connected and Subscribed! Ready to publish\n")
    try:
        while not SHUTDOWN:
            # Direct publish the message
            direct_publisher.publish(
                destination=Topic.of(TOPIC_PREFIX +
                                     f"/python/{unique_name}/{msgSeqNum}"),
                message=outbound_msg)
            msgSeqNum += 1
            # Modifying the outbond message instead of creating a new one
            outbound_msg.solace_message.message_set_binary_attachment_string(
                f'{message_body} --> {msgSeqNum}')
            outbound_msg.solace_message.set_message_application_message_id(
                f'sample_id {msgSeqNum}')
            time.sleep(0.1)
    except KeyboardInterrupt:
        print('\nDisconnecting Messaging Service')
    except PubSubPlusClientError as exception:
        print(f'Received a PubSubPlusClientException: {exception}')
finally:
    print('Terminating Publisher and Receiver')
    direct_publisher.terminate()
Exemplo n.º 20
0
    def run():
        messaging_service = MessagingService.builder().from_properties(
            boot.broker_properties()).build()
        try:
            messaging_service.connect()

            destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT)

            print("Execute Direct Publish - String")
            HowToDirectPublishMessage() \
                .direct_message_publish(messaging_service, destination_name, constants.MESSAGE_TO_SEND)

            print("Execute Direct Publish - Byte Array")
            HowToDirectPublishMessage() \
                .direct_message_publish(messaging_service, destination_name,
                                        bytearray(constants.MESSAGE_TO_SEND, _sol_constants.ENCODING_TYPE))

            print("Execute Direct Publish - String Outbound Message")
            HowToDirectPublishMessage() \
                .direct_message_publish_outbound(messaging_service, destination_name,
                                                 constants.MESSAGE_TO_SEND + str("_outbound based"))

            print("Execute Direct Publish - Byte Array Outbound Message")
            HowToDirectPublishMessage() \
                .direct_message_publish_outbound(messaging_service, destination_name,
                                                 bytearray(constants.MESSAGE_TO_SEND + str("_outbound based"),
                                                           _sol_constants.ENCODING_TYPE))

            print(
                "Execute Direct Publish - Byte Array Outbound Message with props"
            )
            HowToDirectPublishMessage() \
                .direct_message_publish_outbound_properties(messaging_service, destination_name,
                                                            bytearray(constants.MESSAGE_TO_SEND +
                                                                      str("_outbound based with props"),
                                                                      _sol_constants.ENCODING_TYPE))

            print(
                "Execute Direct Publish - String Outbound Message with all props"
            )
            HowToDirectPublishMessage(). \
                direct_message_publish_outbound_with_all_props(messaging_service, destination_name,
                                                               constants.MESSAGE_TO_SEND + str("_outbound based"))

            print("Execute Direct Publish - Generics Outbound Message")
            HowToDirectPublishMessage() \
                .direct_message_publish_outbound_business_obj(messaging_service, destination_name,
                                                              message_obj=MyData('some value'),
                                                              converter=PopoConverter())

            print("Execute Direct Publish - Concurrent testing")
            tasks = []
            with ThreadPoolExecutor() as executor:
                for e in range(
                        10):  # make sure you have try-me1 & try-me2 already
                    destination_name = Topic.of(constants.TOPIC_ENDPOINT_2)
                    if e % 2 == 0:
                        destination_name = Topic.of(constants.TOPIC_ENDPOINT_1)

                    future = executor.submit(
                        HowToDirectPublishMessage().direct_message_publish,
                        messaging_service, destination_name,
                        constants.MESSAGE_TO_SEND)

                    tasks.append(future)
        finally:
            api_metrics = HowToAccessApiMetrics()
            api_metrics.access_individual_api_metrics(
                messaging_service, Metric.TOTAL_MESSAGES_SENT)
            api_metrics.to_string_api_metrics(messaging_service)

            messaging_service.disconnect()
service_handler = ServiceEventHandler()
messaging_service.add_reconnection_listener(service_handler)
messaging_service.add_reconnection_attempt_listener(service_handler)
messaging_service.add_service_interruption_listener(service_handler)

# Create a persistent message publisher and start it
publisher: PersistentMessagePublisher = messaging_service.create_persistent_message_publisher_builder(
).build()
publisher.start_async()

# set a message delivery listener to the publisher
receipt_listener = MessageReceiptListener()
publisher.set_message_publish_receipt_listener(receipt_listener)

# Prepare the destination topic
topic = Topic.of(TOPIC_PREFIX + f'/persistent/pub')

# Prepare outbound message payload and body
message_body = "this is the body of the msg"
outbound_msg_builder = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python")
count = 0
try:
    while True:
        outbound_msg = outbound_msg_builder \
                    .with_application_message_id(f'NEW {count}')\
                    .build(f'{message_body} + {count}')

        publisher.publish(outbound_msg, topic)
service_handler = ServiceEventHandler()
messaging_service.add_reconnection_listener(service_handler)
messaging_service.add_reconnection_attempt_listener(service_handler)
messaging_service.add_service_interruption_listener(service_handler)

# Create a persistent message publisher and start it
publisher: PersistentMessagePublisher = messaging_service.create_persistent_message_publisher_builder(
).build()
publisher.start_async()

# set a message delivery listener to the publisher
receipt_listener = MessageReceiptListener()
publisher.set_message_publish_receipt_listener(receipt_listener)

# Prepare the destination topic
topic = Topic.of(TOPIC_PREFIX)

# Prepare outbound message payload and body
message_body = "this is the body of the msg"
outbound_msg_builder = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python")
count = 0
try:
    while True:
        outbound_msg = outbound_msg_builder \
                    .with_application_message_id(f'NEW {count}')\
                    .build(f'{message_body} + {count}')

        publisher.publish(outbound_msg, topic)
    def consume_just_SDTMapStream_payload(messaging_service,
                                          consumer_subscription):
        """ to consume message"""
        print("consume here testing")
        try:
            # Create a direct message publisher and start it
            direct_publisher = messaging_service.create_direct_message_publisher_builder(
            ).build()
            # Blocking Start thread
            direct_publisher.start()
            print("messaging_service in consumer : ", messaging_service)
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = messaging_service.create_direct_message_receiver_builder() \
                .with_subscriptions(topics).build()
            print("Receiver started...")
            receiver.start()

            # Callback for received messages
            receiver.receive_async(MessageHandlerImpl())
            MESSAGE_TO_SEND = [
                [1, 'c', None,
                 bytearray(b'1'), {
                     'a': 2
                 }, True, 5.5],
                ({
                    "key1": 1,
                    "key2": 2
                }, {
                    "key1": 'value1',
                    "key2": 2
                }, {
                    "key1": tuple(["John", "Doe", "Alice"])
                }), {
                    "key1": 'value1',
                    "key2": True,
                    "key3": {
                        "key31": None,
                        "key32": {
                            "5": 6,
                            "7": {
                                "8": 9
                            }
                        }
                    },
                    "key4": [1.1, None, 3, {
                        "key42": [1, 2, 3]
                    }],
                    "key5": bytearray([0x13, 0x11, 0x10, 0x09, 0x08, 0x01]),
                    "key6": '',
                    "key7": (1, 2, 3)
                }, {
                    "1": 2,
                    "3": {
                        "5": 6,
                        "7": {
                            "8": 9
                        },
                        "11": {
                            "a": "b",
                            "c": [1, 2, 3]
                        }
                    }
                }, 'hello everyone'
            ]
            tasks = []
            with ThreadPoolExecutor() as executor:
                for message in MESSAGE_TO_SEND:
                    future = executor.submit(
                        HowToWorkWithSolaceSDTTypesAndMessages.publish_SDTMap,
                        messaging_service=messaging_service,
                        destination=Topic.of(consumer_subscription),
                        message=message)
                    tasks.append(future)
                # can wait of tasks or wait for for first task using concurrent.futures methods
            # on context exit all pending tasks in the executor must complete
        finally:
            print("Terminating receiver")
            receiver.terminate()
direct_publisher.start()
print(f'Direct Publisher ready? {direct_publisher.is_ready()}')

# Prepare outbound message payload and body
message_body = "this is the body of the msg"
outbound_msg_builder = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python") \

count = 1
print("\nSend a KeyboardInterrupt to stop publishing\n")
try:
    while True:
        while count <= MSG_COUNT:
            topic = Topic.of(TOPIC_PREFIX + f'/python/{count}')
            # Direct publish the message with dynamic headers and payload
            outbound_msg = outbound_msg_builder \
                            .with_application_message_id(f'NEW {count}')\
                            .build(f'{message_body} + {count}')
            direct_publisher.publish(destination=topic, message=outbound_msg)

            print(f'Published message on {topic}')
            count += 1
            time.sleep(0.1)
        print("\n")
        count = 1
        time.sleep(1)

except KeyboardInterrupt:
    print('\nTerminating Publisher')
Exemplo n.º 25
0
    "RideUpdated send",
    kind=SpanKind.PRODUCER,
    attributes={
        "messaging.system": "solace",
        "messaging.destination": outboundTopic,
        "messaging.destination-kind": "topic",
        "messaging.protocol": "jcsmp",
        "messaging.protocol_version": "1.0",
        "messaging.url": os.environ['SOLACE_HOST']}
)

messaging_service = MessagingService.builder().from_properties(broker_props).build()
messaging_service.connect_async()


trace_id = parentSpan.get_context().trace_id
span_id = parentSpan.get_context().span_id
print("parentSpan trace_id  on sender side:" + str(trace_id))
print("parentSpan span_id  on sender side:" + str(span_id))

destination_name = Topic.of(outboundTopic)

outbound_msg = messaging_service.message_builder() \
    .with_property("trace_id", str(trace_id)) \
    .with_property("span_id", str(span_id)) \
    .build("Hello World! This is a message published from Python!")

direct_message_publish(messaging_service, destination_name, outbound_msg)

parentSpan.end()
direct_publisher.start()
print(f'Direct Publisher ready? {direct_publisher.is_ready()}')

# Prepare outbound message payload and body
message_body = "this is the body of the msg"
outbound_msg_builder = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python") \

count = 1
print("\nSend a KeyboardInterrupt to stop publishing\n")
try:
    while True:
        while count <= MSG_COUNT:
            topic = Topic.of(TOPIC_PREFIX + f'/direct/pub/{count}')
            # Direct publish the message with dynamic headers and payload
            outbound_msg = outbound_msg_builder \
                            .with_application_message_id(f'NEW {count}')\
                            .build(f'{message_body} + {count}')
            direct_publisher.publish(destination=topic, message=outbound_msg)

            print(f'Published message on {topic}')
            count += 1
            time.sleep(0.1)
        print("\n")
        count = 1
        time.sleep(1)

except KeyboardInterrupt:
    print('\nTerminating Publisher')