def direct_message_publish_outbound_with_all_props_on_backpressure_wait( messaging_service: MessagingService, destination, message, buffer_capacity, message_count): """ to publish outbound message using back pressure""" try: direct_publish_service = messaging_service.create_direct_message_publisher_builder() \ .on_back_pressure_wait(buffer_capacity=buffer_capacity) \ .build() direct_publish_service.start() outbound_msg = messaging_service.message_builder() \ .with_property("custom_key", "custom_value") \ .with_expiration(SolaceConstants.MESSAGE_EXPIRATION) \ .with_priority(SolaceConstants.MESSAGE_PRIORITY) \ .with_sequence_number(SolaceConstants.MESSAGE_SEQUENCE_NUMBER) \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \ .with_application_message_type("app_msg_type") \ .with_http_content_header("text/html", "utf-8") \ .build(message) for e in range(message_count): direct_publish_service.publish(destination=destination, message=outbound_msg) except PublisherOverflowError: PublisherOverflowError("Queue maximum limit is reached") finally: util.publisher_terminate(direct_publish_service)
def set_core_log_level_by_user(level): """method to set the core api log level by the user Args: level: user defined log level """ MessagingService.set_core_messaging_log_level(level)
def direct_message_publish_outbound_business_obj(messaging_service: MessagingService, destination, message_obj, converter): """ to publish outbound message from a custom object supplied with its own converter""" try: direct_publish_service = messaging_service.create_direct_message_publisher_builder().\ on_back_pressure_reject(buffer_capacity=0).build() publish_start = direct_publish_service.start_async() publish_start.result() outbound_msg = messaging_service.message_builder() \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \ .build(message_obj, converter=converter) direct_publish_service.publish(destination=destination, message=outbound_msg) finally: direct_publish_service.terminate()
def direct_message_publish_outbound_properties( messaging_service: MessagingService, destination, message): """ to publish outbound message with additional properties""" try: direct_publish_service = messaging_service.create_direct_message_publisher_builder( ).build() direct_publish_service.start_async() outbound_msg = messaging_service.message_builder() \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \ .from_properties(constants.CUSTOM_PROPS).build(message) direct_publish_service.publish(destination=destination, message=outbound_msg) finally: direct_publish_service.terminate(0)
def receive_request_and_send_response_message(service: MessagingService, for_requests: TopicSubscription): """Mimics microservice that performs a response Args: service: connected messaging service for_requests: where to expect requests """ request_receiver: RequestReplyMessageReceiver = service.request_reply() \ .create_request_reply_message_receiver_builder().build(for_requests).start() msg, replier = request_receiver.receive_message(timeout=5000) if replier is not None: outbound_msg = service.message_builder().build("pong reply") replier.reply(outbound_msg)
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 direct_message_consume_adding_subscriptions( messaging_service: MessagingService, consumer_subscription: str, listener_topics: list): """ to publish str or byte array type message""" try: topics = [TopicSubscription.of(consumer_subscription)] direct_receive_service = messaging_service.create_direct_message_receiver_builder( ) direct_receive_service = direct_receive_service.with_subscriptions( topics).build() direct_receive_service.start() direct_receive_service.receive_async(MessageHandlerImpl1()) for topic in listener_topics: direct_receive_service.add_subscription( TopicSubscription.of(topic)) print(f"Subscribed to: {consumer_subscription}") while True: global MAX_SLEEP if MAX_SLEEP <= 0: break else: MAX_SLEEP -= 1 time.sleep(1) finally: direct_receive_service.terminate(0)
def direct_message_consume_adding_subscriptions( messaging_service: MessagingService, consumer_subscription: str, listener_topics: list): """ to publish str or byte array type message Args: messaging_service: connected messaging service consumer_subscription: Each topic subscribed listener_topics: list of topics subscribed to """ try: global MAX_SLEEP topics = [TopicSubscription.of(consumer_subscription)] direct_receive_service = messaging_service.create_direct_message_receiver_builder( ) direct_receive_service = direct_receive_service.with_subscriptions( topics).build() direct_receive_service.start() direct_receive_service.receive_async(MessageHandlerImpl1()) for topic in listener_topics: direct_receive_service.add_subscription( TopicSubscription.of(topic)) print(f"Subscribed to: {consumer_subscription}") time.sleep(MAX_SLEEP) finally: direct_receive_service.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()
def run(): try: message = constants.MESSAGE_TO_SEND messaging_service = MessagingService.builder().from_properties( boot.broker_properties()).build() messaging_service.connect() publisher = HowToPublishPersistentMessage.create_persistent_message_publisher( messaging_service) HowToConsumeMessageExclusiveVsSharedMode\ .PersistentMessageReceiverQueueAccessTypes\ .receive_from_durable_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_from_non_durable_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_from_durable_non_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_with_state_change_listener(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .consume_full_message_and_do_ack_using_receive_message(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .consume_using_message_selector(messaging_service, topic, publisher, message) finally: publisher.terminate() messaging_service.disconnect()
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 configure_client_certificate_authentication_customized_settings( props, key_file, key_store_password, key_store_url): """ For a client to use a client certificate authentication scheme, the host event broker must be properly configured for TLS/SSL connections, and Client Certificate Verification must be enabled for the particular Message VPN that the client is connecting to. On client side client certificate needs to be present in a keystore file. Args: props: key_store_password: password for the key store key_store_url: url to the key store file key_file: key file Returns: configured and connected instance of MessagingService ready to be used for messaging tasks """ try: transport_security = TLS.create() \ .with_certificate_validation(True, validate_server_name=False, trust_store_file_path=SamplerUtil.get_trusted_store_dir()) messaging_service = MessagingService.builder() \ .from_properties(props) \ .with_transport_security_strategy(transport_security) \ .with_authentication_strategy(ClientCertificateAuthentication.of(certificate_file=key_store_url, key_file=key_file, key_password=key_store_password)) \ .build(SamplerUtil.get_new_application_id()) return messaging_service.connect() except Exception as exception: print(exception) finally: messaging_service.disconnect()
def direct_message_consume(messaging_service: MessagingService, consumer_subscription: str): """ to publish str or byte array type message""" try: global MAX_SLEEP topics = [TopicSubscription.of(consumer_subscription)] direct_receive_service = messaging_service.create_direct_message_receiver_builder( ) direct_receive_service = direct_receive_service.with_subscriptions( topics).build() direct_receive_service.start() direct_receive_service.receive_async(MessageHandlerImpl()) remaining_time = MAX_SLEEP print(f"Subscribed to: {consumer_subscription}") time.sleep(MAX_SLEEP) finally: api_metrics = HowToAccessApiMetrics() api_metrics.access_individual_api_metrics( messaging_service, Metric.TOTAL_MESSAGES_RECEIVED) api_metrics.to_string_api_metrics(messaging_service) api_metrics.reset_api_metrics(messaging_service) direct_receive_service.terminate()
def connect_using_properties(retries: int, retry_interval: int): """ creates a new instance of message service, that is used to configure direct message instances from config Returns: new connection for Direct messaging Raises: PubSubPlusClientError """ service_config = dict() messaging_service = None try: service_config[ transport_layer_properties.RECONNECTION_ATTEMPTS] = retries service_config[ transport_layer_properties. RECONNECTION_ATTEMPTS_WAIT_INTERVAL] = retry_interval messaging_service = MessagingService.builder().from_properties( boot.broker_properties()).build() messaging_service.connect() return messaging_service except PubSubPlusClientError as exception: raise exception finally: if messaging_service: messaging_service.disconnect()
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(): service = MessagingService.builder().from_properties(boot.broker_properties()).build() service.connect_async() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT print("Execute Direct Consume - String") HowToDirectConsumeBusinessObjectSampler(). \ direct_message_consume_for_business_obj(service, consumer_subscription)
def run(): try: """method to run the sampler""" service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect() finally: service.disconnect()
def direct_message_publish(messaging_service: MessagingService, topic, message): try: # Create a direct message publish service and start it direct_publish_service = messaging_service.create_direct_message_publisher_builder().build() direct_publish_service.start_async() # Publish the message! direct_publish_service.publish(destination=topic, message=message) finally: direct_publish_service.terminate()
def direct_message_consume_for_business_obj( messaging_service: MessagingService, consumer_subscription: str): """ to publish str or byte array type message""" try: global MAX_SLEEP topics = [TopicSubscription.of(consumer_subscription)] direct_receive_service = messaging_service.create_direct_message_receiver_builder( ) direct_receive_service = direct_receive_service.with_subscriptions( topics).build() direct_receive_service.start() direct_receive_service.receive_async(MessageHandlerImpl()) print(f"Subscribed to: {consumer_subscription}") time.sleep(MAX_SLEEP) finally: direct_receive_service.terminate() messaging_service.disconnect()
def direct_message_consume2(messaging_service: MessagingService, consumer_subscription: str): """This method will create an receiver instance to receive str or byte array type message""" try: global MAX_SLEEP topics = [TopicSubscription.of(consumer_subscription)] group_name = ShareName.of('test') direct_receive_service = messaging_service.create_direct_message_receiver_builder( ) direct_receive_service = direct_receive_service.with_subscriptions( topics).build(shared_subscription_group=group_name) direct_receive_service.start() direct_receive_service.receive_async(MessageHandlerImpl2()) print(f"Subscribed to: {consumer_subscription}") time.sleep(MAX_SLEEP) finally: direct_receive_service.terminate() messaging_service.disconnect()
def run(): service = MessagingService.builder().from_properties(boot.broker_properties()).build() service.connect() consumer_subscription = 'request_reply/pub_sub/sampler' reply_timeout = 5000 HowToUseShareNameWithRequestReplyPattern.run_subscribers(service=service, consumer_subscription=consumer_subscription, reply_timeout=reply_timeout) service.disconnect()
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()
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) message: InboundMessage = receiver.receive_message() print(f"the message payload is {message.get_payload_as_string()}")
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 """ requester: RequestReplyMessagePublisher = service.request_reply() \ .create_request_reply_message_publisher_builder().build().start() 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=request_destination, reply_timeout=reply_timeout) # we can get the reply from the future print(publish_request_async.result())
def publish_byte_message_blocking_waiting_for_publisher_confirmation(messaging_service: MessagingService, message_publisher: PersistentMessagePublisher, destination: Topic, message, time_out): """method to publish message using persistent message publisher using blocking publish, i.e publish_await_acknowledgement and wait for the publisher confirmation""" publish_receipt_listener = MessagePublishReceiptListenerImpl() message_publisher.set_message_publish_receipt_listener(publish_receipt_listener) message_publisher.publish_await_acknowledgement(message, destination, time_out) time.sleep(2) metrics = messaging_service.metrics() print(f'Published message count: {metrics.get_value(Metric.PERSISTENT_MESSAGES_SENT)}\n')
def run(): service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect_async() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT listener_topics = ['try-me', 'try-me1', 'try-me2', 'try-me3'] HowToAddAndRemoveSubscriptionSampler() \ .direct_message_consume_adding_subscriptions(service, consumer_subscription, listener_topics) HowToAddAndRemoveSubscriptionSampler() \ .direct_message_consume_removing_subscriptions(service, consumer_subscription, listener_topics)
def direct_message_publish_outbound_with_all_props( messaging_service: MessagingService, destination, message): """ to publish outbound message""" try: direct_publish_service = messaging_service.create_direct_message_publisher_builder( ).build() direct_publish_service.start_async() outbound_msg = messaging_service.message_builder() \ .with_property("custom_key", "custom_value") \ .with_expiration(SolaceConstants.DEFAULT_TIMEOUT_MS) \ .with_priority(1) \ .with_sequence_number(12345) \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \ .with_application_message_type("app_msg_type") \ .with_http_content_header("text/html", _sol_constants.ENCODING_TYPE) \ .build(message) direct_publish_service.publish(destination=destination, message=outbound_msg) finally: direct_publish_service.terminate(0)
def notify_on_direct_publisher_failures(messaging_service: MessagingService, destination_name, message, buffer_capacity, message_count): """ configure direct message publisher to receive notifications about publish failures if any occurred """ try: direct_publish_service = messaging_service.create_direct_message_publisher_builder() \ .on_back_pressure_reject(buffer_capacity=buffer_capacity) \ .build() direct_publish_service.start() publish_failure_listener = PublishFailureListenerImpl() direct_publish_service.set_publish_failure_listener(publish_failure_listener) outbound_msg = messaging_service.message_builder() \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \ .build(message) direct_publish_service.publish(destination=destination_name, message=outbound_msg) finally: direct_publish_service.terminate_async()
def direct_message_publish(messaging_service: MessagingService, destination, message): """ to publish str or byte array type message""" try: direct_publish_service = messaging_service.create_direct_message_publisher_builder( ).build() direct_publish_service.start_async() direct_publish_service.publish(destination=destination, message=message) finally: direct_publish_service.terminate(0)
def create_from_file(): """ creates a new instance of message service, that is used to configure direct message instances from properties file Returns:new connection for Direct messaging """ try: messaging_service = MessagingService.builder().from_file().build() return messaging_service.connect() finally: messaging_service.disconnect()