pip install --upgrade tencentcloud-sdk-python
# API authentication informationcred = credential.Credential(SecretId, SecretKey)httpProfile = HttpProfile()httpProfile.endpoint = NameServerAddressclientProfile = ClientProfile()clientProfile.httpProfile = httpProfile# Create the TDMQ clientclient = tdmq_client.TdmqClient(cred, "ap-guangzhou", clientProfile)# Create CMQ queue request parametersreq = models.CreateCmqQueueRequest()params = {"QueueName": "queue_api",# Below is the dead letter queue configuration"DeadLetterQueueName": "dead_queue_api", # Dead letter queue, which needs to be created first"Policy": 0, # 0: Message has been consumed multiple times but not deleted. 1: `Time-To-Live` has elapsed"MaxReceiveCount": 3 # Maximum receipts. Value range: 1–1000}req.from_json_string(json.dumps(params))# Create a CMQ message queueresp = client.CreateCmqQueue(req)
Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
import osimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")import loggingfrom cmq.account import Accountfrom cmq.queue import Messagefrom cmq.cmq_exception import CMQExceptionBase# `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential# You can get them at https://console.tencentcloud.com/cam/capisecretId = 'AKIDSiiRtxxxx'secretKey = 'GGzSeaM5xxxx'# CMQ service call addressnameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'# Initialize `my_account` and `my_queue`# Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each threadmy_account = Account(nameServerAddress, secretId, secretKey, debug=True)my_account.set_log_level(logging.DEBUG)# Message queue namequeue_name = sys.argv[1] if len(sys.argv) > 1 else "python_queue"my_queue = my_account.get_queue(queue_name)try:# Message contentmsg_body = "I am test message."msg = Message(msg_body)# Send messagesre_msg = my_queue.send_message(msg)# Sending resultprint("Send Message Succeed! MessageBody:%s MessageID:%s" % (msg_body, re_msg.msgId))except CMQExceptionBase as e:print("Send Message Fail! Exception:%s\\n" % e)
Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
queue_name |
import osimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")import loggingfrom cmq.account import Accountfrom cmq.cmq_exception import CMQExceptionBase# `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential# You can get them at https://console.tencentcloud.com/cam/capisecretId = 'AKIDSiiRtxxxx'secretKey = 'GGzSeaM5xxxx'# CMQ service call addressnameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'# Initialize `my_account` and `my_queue`# Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each threadmy_account = Account(nameServerAddress, secretId, secretKey, debug=True)my_account.set_log_level(logging.DEBUG)queue_name = sys.argv[1] if len(sys.argv) > 1 else "python_queue"my_queue = my_account.get_queue(queue_name)try:wait_seconds = 3# Obtain messagesrecv_msg = my_queue.receive_message(wait_seconds)# Specific businessprint("Receive Message Succeed! ReceiptHandle:%s MessageBody:%s MessageID:%s" % (recv_msg.receiptHandle, recv_msg.msgBody, recv_msg.msgId))# Successfully consumed messages are deletedmy_queue.delete_message(recv_msg.receiptHandle)except CMQExceptionBase as e:print("Receive Message Fail! Exception:%s\\n" % e)
Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
queue |
# API authentication informationcred = credential.Credential(SecretId, SecretKey)httpProfile = HttpProfile()httpProfile.endpoint = NameServerAddressclientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = tdmq_client.TdmqClient(cred, "ap-guangzhou", clientProfile)req = models.CreateCmqTopicRequest()params = {"TopicName": "topic_api", # Topic name, which must be unique in the same region under the same account"FilterType": 1, # Used to specify the message match policy for the topic. 1: Tag matching policy. 2: Routing matching policy"MsgRetentionSeconds": 86400 # Message retention period. Value range: 60–86400 seconds (i.e., 1 minute–1 day)}req.from_json_string(json.dumps(params))# Create a topicresp = client.CreateCmqTopic(req)
Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
# API authentication informationcred = credential.Credential(SecretId, SecretKey)httpProfile = HttpProfile()httpProfile.endpoint = NameServerAddressclientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = tdmq_client.TdmqClient(cred, "ap-guangzhou", clientProfile)req = models.CreateCmqSubscribeRequest()params = {"TopicName": "topic_api", # Name of the topic for which to create a subscription"SubscriptionName": "sub", # Subscription name"Protocol": "queue", # Subscription protocol. Currently, two protocols are supported: HTTP and queue. To use the HTTP protocol, you need to build your own web server to receive messages. With the queue protocol, messages are automatically pushed to a CMQ queue and you can pull them concurrently."Endpoint": "topic_queue_api", # Endpoint that receives notifications, which varies by protocol: for HTTP, the endpoint must start with `http://`, and the `host` can be a domain or IP; for queue, `QueueName` should be entered."NotifyStrategy": "BACKOFF_RETRY", # CMQ push server retry policy. Valid values: 1) BACKOFF_RETRY; 2) EXPONENTIAL_DECAY_RETRY."FilterTag": ["TAG"], # Message filter tag (used for message filtering). The number of tags cannot exceed 5.# "BindingKey": ["a.b.c"], # The number of `BindingKey` cannot exceed 5, and the length of each `BindingKey` cannot exceed 64 bytes. This field indicates the filtering policy for subscribing to and receiving messages."NotifyContentFormat": "SIMPLIFIED" # Push content format. Valid values: 1. JSON; 2. SIMPLIFIED, i.e., the raw format. If `Protocol` is `queue`, this value must be `SIMPLIFIED`. If `Protocol` is `http`, both options are acceptable, and the default value is `JSON`.}req.from_json_string(json.dumps(params))# Create a subscriptionresp = client.CreateCmqSubscribe(req)
BindingKey
and FilterTag
should be set according to the type of subscribed topic; otherwise, they will be invalid.Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
my_topic
to publish messages.import osimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")import loggingfrom cmq.account import Accountfrom cmq.cmq_exception import *from cmq.topic import *# `secretId` and `secretKey` of your Tencent Cloud account, which should be kept confidential# You can get them at https://console.tencentcloud.com/cam/capisecretId = 'AKIDSiiRtxxxx'secretKey = 'GGzSeaM5xxxx'# CMQ service call addressnameServerAddress = 'https://cmq-gz.public.tencenttdmq.com'try:# Initialize `my_account`# Account class objects are not thread-safe. If you need to use them in multiple threads, initialize them for each threadmy_account = Account(nameServerAddress, secretId, secretKey, debug=True)my_account.set_log_level(logging.DEBUG)# Topic nametopic_name = sys.argv[1] if len(sys.argv) > 1 else "python_topic_route"my_topic = my_account.get_topic(topic_name)except CMQExceptionBase as e:print("Exception:%s\\n" % e)
Parameter | Description |
NameServerAddress | API call address, which can be copied from Queue Service > API Request Address in the TDMQ for CMQ console. |
SecretId, SecretKey | TencentCloud API key, which can be copied on the Access Key > API Key Management page in the CAM console. |
topic_name | Topic subscription name, which can be obtained on the Topic Subscription page in the TDMQ for CMQ console. |
# Message tagtags = ["TAG", "TAG1", "TAG2"]for tag in tags:# Send tag messagesmessage = Message("this is a test TAG message. TAG:" + tag, [tag])re_msg = my_topic.publish_message(message)# Sending resultprint("Send Message Succeed! MessageBody:%s MessageID:%s" % (message.msgBody, re_msg.msgId))
# Message route informationroutes = ["a.b.c", "a.b.x", "a.c.d", "x.y.z", "x.y.c"]for route in routes:message = Message("this is a test route message. Route:" + route)# Send route messagesre_msg = my_topic.publish_message(message, route)# Sending resultprint("Send Message Succeed! MessageBody:%s MessageID:%s" % (message.msgBody, re_msg.msgId))
Was this page helpful?