主题使用示例

本文介绍使用Python SDK发送SMQ消息到主题时的前提条件及示例代码。

前提条件

消息体编码选择

对消息体是否进行Base64编码,请参见消息体编码选择指南

发布消息

  • 运行publishmessage.py发布多条消息到主题中,命令如下:

    python publishmessage.py MyTopic1        

    返回结果如下:

    ==========Publish Message To Topic==========
    TopicName:MyTopic1
    MessageCount:3
    
    Publish Raw Message Succeed. MessageBody:I am test message 0. MessageID:4EA4CF419C3A7FC67FA95077****0001
    Publish Raw Message Succeed. MessageBody:I am test message 1. MessageID:4EA4CF419C3A7FC67FA95077****0002
    Publish Raw Message Succeed. MessageBody:I am test message 2. MessageID:4EA4CF419C3A7FC67FA95077****0003
    Publish Base64 Encoded Message Succeed. MessageBody:I am test message 0. MessageID:4EA4CF419C3A7FC67FA95077****0004
    Publish Base64 Encoded Message Succeed. MessageBody:I am test message 1. MessageID:4EA4CF419C3A7FC67FA95077****0005
    Publish Base64 Encoded Message Succeed. MessageBody:I am test message 2. MessageID:4EA4CF419C3A7FC67FA95077****0006
  • 核心代码:

    my_account = Account(endpoint, accid, acckey, token)
    topic_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleTopic"
    my_topic = my_account.get_topic(topic_name)
    
    msg_count = 3
    print("%sPublish Message To Topic%s\nTopicName:%s\nMessageCount:%s\n" % (10*"=", 10*"=", topic_name, msg_count))
    
    for i in range(msg_count):
        try:
            msg_body = u"I am test message %s." % i
            msg = TopicMessage(msg_body)
            re_msg = my_topic.publish_message(msg)
            print("Publish Raw Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id))
        except MNSExceptionBase as e:
            if e.type == "TopicNotExist":
                print("Topic not exist, please create it.")
                sys.exit(1)
            print("Publish Raw Message Fail. Exception:%s" % e)
    
    for i in range(msg_count):
        try:
            msg_body = u"I am test message %s." % i
            msg = Base64TopicMessage(msg_body)
            re_msg = my_topic.publish_message(msg)
            print("Publish Base64 Encoded Message Succeed. MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id))
        except MNSExceptionBase as e:
            if e.type == "TopicNotExist":
                print("Topic not exist, please create it.")
                sys.exit(1)
            print("Publish Base64 Encoded Message Fail. Exception:%s" % e)