### Install MQ HTTP SDK using pip Source: https://github.com/aliyunmq/mq-http-python-sdk/blob/master/README.rst Use this command to install the MQ HTTP SDK. Ensure pip is installed first. ```bash pip install mq_http_sdk ``` -------------------------------- ### Accessing Message Properties Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Demonstrates how to retrieve various properties from a message object, such as its key, region, start delivery time, sharding key, and transaction check immunity time. ```python print(msg.get_message_key()) # "unique-key-001" print(msg.get_property("region")) # "cn-hangzhou" print(msg.get_start_deliver_time()) # 0 (or epoch ms if set) print(msg.get_sharding_key()) # "order-12345" print(msg.get_trans_check_immunity_time()) # 0 (or seconds if set) ``` -------------------------------- ### Create Transaction Producer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Get an MQTransProducer for publishing messages as part of a distributed transaction. Supports commit, rollback, and check-back operations. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) trans_producer = mq_client.get_trans_producer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTransTopic", group_id="GID_MyTransGroup" ) ``` -------------------------------- ### MQClient Initialization Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Initializes the MQClient, which is the entry point for all SDK operations. It handles authentication and HTTP communication with the Aliyun MQ service. Supports basic authentication, STS temporary credentials, and debug logging. ```APIDOC ## MQClient — Initialize the Client `MQClient` is the root object for all SDK operations. It establishes the authenticated HTTP connection to the Aliyun MQ endpoint and serves as a factory for producers and consumers. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_tool import MQLogger import logging # Basic client (no STS token) mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) # Client with STS temporary credentials mq_client_sts = MQClient( host="https://.mqrest.cn-hangzhou.aliyuncs.com", access_id="STS_ACCESS_ID", access_key="STS_ACCESS_KEY", security_token="STS_SECURITY_TOKEN" ) # Client with debug logging enabled logger = MQLogger.get_logger( log_name="my_mq_app", log_file="/var/log/mq_sdk.log", log_level=logging.DEBUG ) mq_client_debug = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY", debug=True, logger=logger ) # Configure connection settings mq_client.set_connection_timeout(30) # 30-second timeout mq_client.set_keep_alive(True) # reuse TCP connections ``` ``` -------------------------------- ### Initialize MQClient Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Instantiate MQClient for basic authentication, STS temporary credentials, or with debug logging enabled. Configure connection timeouts and keep-alive settings. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_tool import MQLogger import logging # Basic client (no STS token) mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) # Client with STS temporary credentials mq_client_sts = MQClient( host="https://.mqrest.cn-hangzhou.aliyuncs.com", access_id="STS_ACCESS_ID", access_key="STS_ACCESS_KEY", security_token="STS_SECURITY_TOKEN" ) # Client with debug logging enabled logger = MQLogger.get_logger( log_name="my_mq_app", log_file="/var/log/mq_sdk.log", log_level=logging.DEBUG ) mq_client_debug = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY", debug=True, logger=logger ) # Configure connection settings mq_client.set_connection_timeout(30) # 30-second timeout mq_client.set_keep_alive(True) # reuse TCP connections ``` -------------------------------- ### Configuring SDK Logging with MQLogger Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Initializes a rotating-file logger for SDK diagnostics using MQLogger. Configure the log name, file path, and logging level. The logger can be passed to MQClient for SDK-level diagnostics. ```python import logging from mq_http_sdk.mq_tool import MQLogger from mq_http_sdk.mq_client import MQClient logger = MQLogger.get_logger( log_name="mq_app", log_file="/var/log/mq_app.log", log_level=logging.INFO ) mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY", logger=logger ) # Change log level at runtime mq_client.set_log_level(logging.DEBUG) # Disable logging mq_client.close_log() ``` -------------------------------- ### Create Standard Producer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Obtain an MQProducer instance bound to a specific topic for publishing standard, scheduled, or ordered messages. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) producer = mq_client.get_producer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic" ) ``` -------------------------------- ### Create Consumer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Instantiate an MQConsumer to receive messages from a topic and consumer group. Supports optional message tag filtering. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) # Consumer with tag filter consumer = mq_client.get_consumer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic", consumer="GID_MyConsumerGroup", message_tag="order" # optional: only receive messages tagged "order" ) # Consumer without tag filter consumer_all = mq_client.get_consumer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic", consumer="GID_MyConsumerGroup" ) ``` -------------------------------- ### Publishing Messages Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Demonstrates how to publish plain, scheduled, and ordered messages using the `producer.publish_message` method. Includes setting message properties, keys, and sharding keys. ```APIDOC ## Publish Plain Message ### Description Publishes a standard message with a body and an optional tag and key. ### Method `producer.publish_message(msg: TopicMessage)` ### Parameters - `msg` (TopicMessage): The message object to publish. - `message_body` (str): The content of the message. - `message_tag` (str, optional): A tag for message filtering. - `message_key` (str, optional): A business-defined key for the message. - `properties` (dict, optional): Custom key-value properties. - `start_deliver_time` (int, optional): Epoch milliseconds for scheduled delivery. - `sharding_key` (str, optional): Key used for message ordering within a partition. ### Request Example ```python from mq_http_sdk.mq_message import TopicMessage msg = TopicMessage(message_body="Hello, MQ!", message_tag="greet") msg.set_message_key("unique-key-001") msg.put_property("region", "cn-hangzhou") # producer.publish_message(msg) ``` ### Response #### Success Response - `message_id` (str): The unique ID of the published message. - `message_body_md5` (str): The MD5 hash of the message body. ### Error Handling - `MQServerException`: For server-side errors. - `MQClientException`: For client-side errors. ## Publish Scheduled Message ### Description Publishes a message that will be delivered at a specified future time. ### Method `producer.publish_message(msg: TopicMessage)` ### Parameters - `msg` (TopicMessage): The message object to publish. - `message_body` (str): The content of the message. - `start_deliver_time` (int): Epoch milliseconds for when the message should be delivered. ### Request Example ```python import time from mq_http_sdk.mq_message import TopicMessage delayed_msg = TopicMessage(message_body="Scheduled payload") delayed_msg.set_start_deliver_time(int(time.time() * 1000) + 10000) # 10 seconds from now # producer.publish_message(delayed_msg) ``` ## Publish Ordered Message ### Description Publishes a message that will be consumed in a specific order based on a sharding key. ### Method `producer.publish_message(msg: TopicMessage)` ### Parameters - `msg` (TopicMessage): The message object to publish. - `message_body` (str): The content of the message. - `sharding_key` (str): The key that determines the partition for ordering. ### Request Example ```python from mq_http_sdk.mq_message import TopicMessage order_msg = TopicMessage(message_body="Order event payload") order_msg.set_sharding_key("order-12345") # producer.publish_message(order_msg) ``` ``` -------------------------------- ### Publish Plain Message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Publishes a standard message to a topic. Includes optional business key and custom properties. Handles potential server and client exceptions. ```python msg = TopicMessage(message_body="Hello, MQ!", message_tag="greet") msg.set_message_key("unique-key-001") # optional business key msg.put_property("region", "cn-hangzhou") # custom property try: result = producer.publish_message(msg) print("Published: id=%s md5=%s" % (result.message_id, result.message_body_md5)) except MQServerException as e: print("Server error: type=%s message=%s reqId=%s" % (e.type, e.message, e.request_id)) except MQClientException as e: print("Client error: %s" % e.get_info()) ``` -------------------------------- ### Publish Transactional Half-Message with MQTransProducer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Use `publish_message` to send a transactional half-message. The `receipt_handle` returned is crucial for subsequent commit or rollback operations. Ensure the `trans_check_immunity_time` is set appropriately to control the initial check-back window. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_producer import TopicMessage from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) trans_producer = mq_client.get_trans_producer( "MQ_INST_XXXXXXXXX", "MyTransTopic", "GID_TransGroup" ) msg = TopicMessage(message_body="Transfer: account A -> B, amount=100") msg.set_trans_check_immunity_time(10) # first check-back no sooner than 10 seconds try: result = trans_producer.publish_message(msg) half_receipt = result.receipt_handle print("Half-message sent, id=%s" % result.message_id) # Simulate local transaction execution local_tx_success = True # replace with actual DB transaction if local_tx_success: trans_producer.commit(half_receipt) print("Transaction committed.") else: trans_producer.rollback(half_receipt) print("Transaction rolled back.") except MQServerException as e: print("Transaction error [%s]: %s" % (e.type, e.message)) ``` -------------------------------- ### Consume and Check-Back Half-Messages with MQTransProducer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Implement `consume_half_message` to handle server check-backs for messages with unknown transaction status. After re-verifying the local transaction outcome, use `commit` or `rollback` with the message's `receipt_handle`. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) trans_producer = mq_client.get_trans_producer( "MQ_INST_XXXXXXXXX", "MyTransTopic", "GID_TransGroup" ) try: half_messages = trans_producer.consume_half_message(batch_size=4, wait_seconds=10) for msg in half_messages: print("Check-back half-msg: id=%s body=%s" % (msg.message_id, msg.message_body)) # Re-check local DB for transaction outcome tx_committed = check_local_transaction(msg.message_id) # user-defined function if tx_committed: trans_producer.commit(msg.receipt_handle) else: trans_producer.rollback(msg.receipt_handle) except MQServerException as e: if e.type == "MessageNotExist": print("No half-messages to check.") else: raise ``` -------------------------------- ### Compose a TopicMessage with Custom Properties and Delivery Controls Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt The `TopicMessage` object allows setting message body, tags, keys, custom properties, scheduled delivery times, sharding keys, and transaction immunity periods. Note that custom properties should not contain special characters like '&', '"', "'", '<', '>', ':', '|'. ```python from mq_http_sdk.mq_producer import TopicMessage import time msg = TopicMessage() # Core fields msg.set_message_body("{'event': 'order_placed', 'order_id': 9876}") msg.set_message_tag("ecommerce") # Business/search key (searchable in console) msg.set_message_key("order-9876") # Custom arbitrary properties (no special characters: & " ' < > : |) msg.put_property("source", "web") msg.put_property("priority", "high") # Scheduled delivery (Unix epoch milliseconds, max 3 days ahead) msg.set_start_deliver_time(int(time.time() * 1000) + 60_000) # 1 minute from now # Partition ordering key msg.set_sharding_key("customer-42") # Transaction check-back immunity window (seconds) msg.set_trans_check_immunity_time(30) print("body=%s tag=%s key=%s props=%s" % ( msg.message_body, msg.message_tag, msg.properties.get("KEYS"), msg.properties)) # body={'event': 'order_placed', 'order_id': 9876} tag=ecommerce key=order-9876 # props={'KEYS': 'order-9876', 'source': 'web', 'priority': 'high', # '__STARTDELIVERTIME': '1700000060000', '__SHARDINGKEY': 'customer-42') ``` -------------------------------- ### Publish Standard Message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Send a TopicMessage to a configured topic. The response includes the message ID and MD5 hash upon successful publication. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_producer import TopicMessage from mq_http_sdk.mq_exception import MQServerException, MQClientException import time mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) producer = mq_client.get_producer("MQ_INST_XXXXXXXXX", "MyTopic") ``` -------------------------------- ### Consume Ordered Messages with MQConsumer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Consumes messages in strict partition order. All messages in a partition must be acknowledged before the next batch is delivered. Handles 'MessageNotExist' exceptions and acknowledges processed messages. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) consumer = mq_client.get_consumer("MQ_INST_XXXXXXXXX", "MyOrderTopic", "GID_OrderGroup") try: messages = consumer.consume_message_orderly(batch_size=4, wait_seconds=5) receipt_handles = [] for msg in messages: print("Ordered msg: id=%s sharding_key=%s body=%s" % ( msg.message_id, msg.get_sharding_key(), msg.message_body)) receipt_handles.append(msg.receipt_handle) if receipt_handles: consumer.ack_message(receipt_handles) except MQServerException as e: if e.type == "MessageNotExist": print("No ordered messages.") else: raise ``` -------------------------------- ### MQClient.get_consumer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Creates and returns an `MQConsumer` instance. The consumer is configured for a specific topic, consumer group, and can optionally filter messages by a tag. ```APIDOC ## MQClient.get_consumer — Create a Consumer Returns an `MQConsumer` bound to a topic, consumer group, and optional tag filter. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) # Consumer with tag filter consumer = mq_client.get_consumer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic", consumer="GID_MyConsumerGroup", message_tag="order" # optional: only receive messages tagged "order" ) # Consumer without tag filter consumer_all = mq_client.get_consumer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic", consumer="GID_MyConsumerGroup" ) ``` ``` -------------------------------- ### MQClient.get_producer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Creates and returns an `MQProducer` instance associated with a specific topic. This producer is used for publishing standard, scheduled, or ordered messages. ```APIDOC ## MQClient.get_producer — Create a Standard Producer Returns an `MQProducer` bound to a specific topic. Use this to publish normal, scheduled, or ordered messages. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) producer = mq_client.get_producer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTopic" ) ``` ``` -------------------------------- ### MQClient.get_trans_producer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Creates and returns an `MQTransProducer` for publishing messages as part of a distributed transaction. Supports message commit, rollback, and check-back consumption. ```APIDOC ## MQClient.get_trans_producer — Create a Transaction Producer Returns an `MQTransProducer` for publishing half-messages as part of a distributed transaction, with support for commit/rollback and half-message check-back consumption. ```python from mq_http_sdk.mq_client import MQClient mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) trans_producer = mq_client.get_trans_producer( instance_id="MQ_INST_XXXXXXXXX", topic_name="MyTransTopic", group_id="GID_MyTransGroup" ) ``` ``` -------------------------------- ### Handling MQ Exceptions Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Provides comprehensive error handling for MQ operations using specific exception types like MQServerException, MQClientNetworkException, and MQClientParameterException. Catches service-level errors, network issues, and parameter validation failures. ```python from mq_http_sdk.mq_exception import ( MQServerException, MQClientNetworkException, MQClientParameterException ) from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_producer import TopicMessage mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) producer = mq_client.get_producer("MQ_INST_XXXXXXXXX", "MyTopic") consumer = mq_client.get_consumer("MQ_INST_XXXXXXXXX", "MyTopic", "GID_MyGroup") # Publishing with full error handling try: result = producer.publish_message(TopicMessage("test body")) print("OK: id=%s" % result.message_id) except MQClientParameterException as e: # Invalid parameter (empty body, bad tag length, forbidden property chars, etc.) print("Bad parameter [%s]: %s" % (e.type, e.message)) except MQClientNetworkException as e: # DNS failure, TCP timeout, connection refused, etc. print("Network error [%s]: %s" % (e.type, e.message)) except MQServerException as e: # Service-level errors with request tracing # Common types: TopicNotExist, AccessDenied, InvalidArgument print("Server error [%s]: %s reqId=%s hostId=%s" % ( e.type, e.message, e.request_id, e.host_id)) if e.sub_errors: for sub in e.sub_errors: print(" sub-error: %s" % sub) # Consuming: MessageNotExist is normal (no messages in queue) try: msgs = consumer.consume_message(batch_size=1, wait_seconds=3) except MQServerException as e: if e.type == "MessageNotExist": print("Queue empty, try again later.") else: print("Unexpected server error [%s]: %s" % (e.type, e.message)) raise ``` -------------------------------- ### MQProducer.publish_message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Publishes a standard `TopicMessage` to the configured topic. On successful publication, it returns the `TopicMessage` object including the assigned `message_id` and `message_body_md5`. ```APIDOC ## MQProducer.publish_message — Publish a Standard Message Sends a `TopicMessage` to the configured topic. Returns a `TopicMessage` with `message_id` and `message_body_md5` on success. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_producer import TopicMessage from mq_http_sdk.mq_exception import MQServerException, MQClientException import time mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) producer = mq_client.get_producer("MQ_INST_XXXXXXXXX", "MyTopic") ``` -------------------------------- ### MQConsumer.consume_message_orderly Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Consumes messages in strict partition order. All messages within a partition must be acknowledged before the next batch from that partition is delivered. ```APIDOC ## MQConsumer.consume_message_orderly — Poll for Ordered Messages ### Description Consumes messages in strict partition order. All messages in a partition must be acknowledged before the next batch in that partition is delivered. ### Method `consumer.consume_message_orderly(batch_size: int, wait_seconds: int)` ### Parameters - `batch_size` (int): The maximum number of messages to retrieve per partition. - `wait_seconds` (int): The maximum time in seconds to wait for messages. ### Request Example ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) consumer = mq_client.get_consumer("MQ_INST_XXXXXXXXX", "MyOrderTopic", "GID_OrderGroup") try: messages = consumer.consume_message_orderly(batch_size=4, wait_seconds=5) receipt_handles = [] for msg in messages: print("Ordered msg: id=%s sharding_key=%s body=%s" % ( msg.message_id, msg.get_sharding_key(), msg.message_body)) receipt_handles.append(msg.receipt_handle) if receipt_handles: consumer.ack_message(receipt_handles) except MQServerException as e: if e.type == "MessageNotExist": print("No ordered messages.") else: raise ``` ### Response #### Success Response - `messages` (list): A list of ordered `Message` objects. - `message_id` (str): The unique ID of the message. - `message_body` (str): The content of the message. - `sharding_key` (str): The sharding key used for ordering. - `receipt_handle` (str): The handle required for acknowledging the message. #### Error Response - `MQServerException` with `type` "MessageNotExist": If no ordered messages are available. ### Acknowledgment - `consumer.ack_message(receipt_handles: list)`: Acknowledges a list of ordered messages. This is crucial for progressing through partitions. ``` -------------------------------- ### Publish Ordered Message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Publishes a message that requires strict ordering within a partition. A sharding key is set to ensure messages with the same key are processed in order. Handles potential server exceptions. ```python # --- Ordered message: set sharding key for partition ordering --- order_msg = TopicMessage(message_body="Order event payload") order_msg.set_sharding_key("order-12345") try: result = producer.publish_message(order_msg) print("Order message id=%s" % result.message_id) except MQServerException as e: print("Server error [%s]: %s" % (e.type, e.message)) ``` -------------------------------- ### Consume Messages with MQConsumer Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Polls for messages from a topic using long-polling. Messages must be acknowledged within 300 seconds. Handles 'MessageNotExist' exceptions and acknowledges successful messages. ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) consumer = mq_client.get_consumer("MQ_INST_XXXXXXXXX", "MyTopic", "GID_MyConsumerGroup") receipt_handles = [] try: messages = consumer.consume_message(batch_size=4, wait_seconds=10) for msg in messages: print("id=%s body=%s tag=%s consumed_times=%d" % ( msg.message_id, msg.message_body, msg.message_tag, msg.consumed_times)) print(" key=%s region=%s" % (msg.get_message_key(), msg.get_property("region"))) receipt_handles.append(msg.receipt_handle) except MQServerException as e: if e.type == "MessageNotExist": print("No messages available right now.") else: raise # Acknowledge successful processing if receipt_handles: try: consumer.ack_message(receipt_handles) print("Acknowledged %d messages." % len(receipt_handles)) except MQServerException as e: # Partial failures reported in e.sub_errors print("Ack partial failure: %s" % e.sub_errors) ``` -------------------------------- ### Publish Scheduled Message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Publishes a message that will be delivered at a specified future time. The delivery time is set in epoch milliseconds. Handles potential server exceptions. ```python # --- Scheduled (timer) message: deliver 10 seconds from now --- delayed_msg = TopicMessage(message_body="Scheduled payload") delayed_msg.set_start_deliver_time(int(time.time() * 1000) + 10000) # epoch ms try: result = producer.publish_message(delayed_msg) print("Scheduled message id=%s" % result.message_id) except MQServerException as e: print("Server error [%s]: %s" % (e.type, e.message)) ``` -------------------------------- ### Inspect Received Message Properties with Message Object Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt The `Message` object, returned by `consume_message`, provides access to all message metadata including ID, body, tag, MD5, consumption counts, timestamps, and the `receipt_handle` required for acknowledgment. ```python # msg is a Message instance returned from consumer.consume_message() print(msg.message_id) # "0A57FE7B0000159200000000000001A8" print(msg.message_body) # "Hello, MQ!" print(msg.message_tag) # "greet" print(msg.message_body_md5) # "AB1234..." print(msg.consumed_times) # 1 (increments on each redelivery) print(msg.publish_time) # 1700000000000 (epoch ms) print(msg.first_consume_time) # 1700000010000 (epoch ms) print(msg.next_consume_time) # 1700000310000 (epoch ms, redelivery time if not acked) print(msg.receipt_handle) # "bq2sa..." (pass to ack_message) ``` -------------------------------- ### TopicMessage Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt `TopicMessage` is the data object used when publishing. It carries the message body, routing tag, custom properties, and special delivery controls. ```APIDOC ## TopicMessage — Compose a Message `TopicMessage` is the data object used when publishing. It carries the message body, routing tag, custom properties, and special delivery controls. ### Methods - **set_message_body(body: str)**: Sets the message body. - **set_message_tag(tag: str)**: Sets the message tag. - **set_message_key(key: str)**: Sets the message key. - **put_property(key: str, value: str)**: Adds a custom property. - **set_start_deliver_time(timestamp_ms: int)**: Sets the scheduled delivery time in milliseconds since epoch. - **set_sharding_key(key: str)**: Sets the sharding key for partition ordering. - **set_trans_check_immunity_time(seconds: int)**: Sets the transaction check-back immunity window in seconds. ### Request Example ```python from mq_http_sdk.mq_producer import TopicMessage import time msg = TopicMessage() msg.set_message_body("{'event': 'order_placed', 'order_id': 9876}") msg.set_message_tag("ecommerce") msg.set_message_key("order-9876") msg.put_property("source", "web") msg.set_start_deliver_time(int(time.time() * 1000) + 60_000) msg.set_sharding_key("customer-42") msg.set_trans_check_immunity_time(30) ``` ``` -------------------------------- ### Message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt `Message` is the data object returned by `consume_message`. It provides all delivery metadata and property accessors. ```APIDOC ## Message — Inspect a Received Message `Message` is the data object returned by `consume_message`. It provides all delivery metadata and property accessors. ### Properties - **message_id** (string): The ID of the message. - **message_body** (string): The message body. - **message_tag** (string): The message tag. - **message_body_md5** (string): The MD5 hash of the message body. - **consumed_times** (integer): The number of times the message has been consumed. - **publish_time** (integer): The publish time of the message in epoch milliseconds. - **first_consume_time** (integer): The first consume time of the message in epoch milliseconds. - **next_consume_time** (integer): The next consume time of the message in epoch milliseconds (redelivery time if not acked). - **receipt_handle** (string): The receipt handle for the message (used for acknowledging). ``` -------------------------------- ### MQTransProducer.publish_message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Sends a transaction half-message. The message remains invisible to consumers until committed. The receipt_handle in the result must be used to commit or roll back the transaction. ```APIDOC ## MQTransProducer.publish_message — Publish a Transaction Half-Message Sends a transaction half-message. The message remains invisible to consumers until committed. The `receipt_handle` in the result must be used to commit or roll back the transaction. ### Method POST ### Endpoint /api/v2/transactions/messages ### Parameters #### Request Body - **message_body** (string) - Required - The message body. - **message_tag** (string) - Optional - The message tag. - **message_key** (string) - Optional - The message key. - **properties** (object) - Optional - Custom properties. - **sharding_key** (string) - Optional - The sharding key for partition ordering. - **trans_check_immunity_time** (integer) - Optional - The time in seconds for transaction check-back immunity. ### Request Example ```python from mq_http_sdk.mq_producer import TopicMessage msg = TopicMessage(message_body="Transfer: account A -> B, amount=100") msg.set_trans_check_immunity_time(10) result = trans_producer.publish_message(msg) ``` ### Response #### Success Response (200) - **message_id** (string) - The ID of the published message. - **receipt_handle** (string) - The receipt handle for the transaction. ``` -------------------------------- ### MQConsumer.consume_message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt Polls the topic for messages. It can retrieve up to `batch_size` messages and supports long-polling with `wait_seconds`. Messages must be acknowledged within 300 seconds. ```APIDOC ## MQConsumer.consume_message — Poll for Messages ### Description Long-polls the topic for up to `batch_size` messages (1–16). Returns a list of `Message` objects. Messages must be acknowledged within 300 seconds via `ack_message` or they will be redelivered. ### Method `consumer.consume_message(batch_size: int, wait_seconds: int)` ### Parameters - `batch_size` (int): The maximum number of messages to retrieve (1-16). - `wait_seconds` (int): The maximum time in seconds to wait for messages (long-polling). ### Request Example ```python from mq_http_sdk.mq_client import MQClient from mq_http_sdk.mq_exception import MQServerException mq_client = MQClient( host="http://.mqrest.cn-hangzhou.aliyuncs.com", access_id="YOUR_ACCESS_ID", access_key="YOUR_ACCESS_KEY" ) consumer = mq_client.get_consumer("MQ_INST_XXXXXXXXX", "MyTopic", "GID_MyConsumerGroup") receipt_handles = [] try: messages = consumer.consume_message(batch_size=4, wait_seconds=10) for msg in messages: print("id=%s body=%s tag=%s consumed_times=%d" % ( msg.message_id, msg.message_body, msg.message_tag, msg.consumed_times)) print(" key=%s region=%s" % (msg.get_message_key(), msg.get_property("region"))) receipt_handles.append(msg.receipt_handle) except MQServerException as e: if e.type == "MessageNotExist": print("No messages available right now.") else: raise # Acknowledge successful processing if receipt_handles: try: consumer.ack_message(receipt_handles) print("Acknowledged %d messages." % len(receipt_handles)) except MQServerException as e: # Partial failures reported in e.sub_errors print("Ack partial failure: %s" % e.sub_errors) ``` ### Response #### Success Response - `messages` (list): A list of `Message` objects. - `message_id` (str): The unique ID of the message. - `message_body` (str): The content of the message. - `message_tag` (str): The tag associated with the message. - `consumed_times` (int): The number of times the message has been consumed. - `receipt_handle` (str): The handle required for acknowledging the message. - `message_key` (str): The business key of the message. - `properties` (dict): Custom properties of the message. #### Error Response - `MQServerException` with `type` "MessageNotExist": If no messages are available. ### Acknowledgment - `consumer.ack_message(receipt_handles: list)`: Acknowledges a list of messages using their receipt handles. This must be done within 300 seconds of consumption. ``` -------------------------------- ### MQTransProducer.consume_half_message Source: https://context7.com/aliyunmq/mq-http-python-sdk/llms.txt The MQ server calls back to retrieve half-messages whose local transaction status is unknown. The producer polls for these and commits or rolls back each one. ```APIDOC ## MQTransProducer.consume_half_message — Check-Back Half-Messages The MQ server calls back to retrieve half-messages whose local transaction status is unknown (e.g., after a producer crash). The producer polls for these and commits or rolls back each one. ### Method GET ### Endpoint /api/v2/transactions/messages ### Query Parameters - **batch_size** (integer) - Optional - The maximum number of messages to return. - **wait_seconds** (integer) - Optional - The maximum time in seconds to wait for messages. ### Response #### Success Response (200) - **messages** (array) - An array of half-messages. - **message_id** (string) - The ID of the message. - **message_body** (string) - The message body. - **receipt_handle** (string) - The receipt handle for the transaction. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.