本文介绍如何使用Python SDK中的sample代码,完成创建队列、发送消息、接收删除消息和删除队列操作。

步骤一:准备工作

  1. 下载最新版Python SDK,解压后进入mns_python_sdk子目录。
  2. 打开sample.cfg文件,配置AccessKeyId、AccessKeySecret和Endpoint。
    • AccessKeyId、AccessKeySecret
    • Endpoint
      • 访问MNS的接入地址,登录MNS控制台,单击右上角获取Endpoint查看。
      • 不同地域的接入地址不同。
    • SecurityToken
      • 阿里云访问控制服务提供的短期访问权限凭证,直接使用阿里云账号或者子账号访问不需要配置该项,详情请参见什么是STS
  3. 进入sample目录,后续使用的脚本都在该目录。

步骤二:创建队列

运行createqueue.py创建队列。默认创建的队列名称是MySampleQueue,也可以通过参数指定队列名称。队列详细信息请参见Queue

  • 运行以下命令:
    $python createqueue.py MyQueue1         
     Create Queue Succeed! QueueName:MyQueue1
  • 核心代码

    endpointaccidacckeytoken从步骤一的配置文件中读取。

    #init my_account, my_queue
    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    my_queue = my_account.get_queue(queue_name)
    
    #you can get more information of QueueMeta from mns/queue.py
    queue_meta = QueueMeta()
    try:
        queue_url = my_queue.create(queue_meta)
        print "Create Queue Succeed! QueueName:%s\n" % queue_name
    except MNSExceptionBase, e:
        if e.type == "QueueAlreadyExist":
            print "Queue already exist, please delete it before creating or use it directly."
            sys.exit(0)
        print "Create Queue Fail! Exception:%s\n" % e
    					

步骤三:发送消息

运行sendmessage.py,发送多条消息到队列中。如果步骤二指定了队列名称,这里同样通过参数指定队列名称。消息详细信息请参见QueueMessage

  • 运行以下命令:
    $python sendmessage.py MyQueue1
    ==========Send Message To Queue==========
    QueueName:MyQueue1
    MessageCount:3
    
    Send Message Succeed! MessageBody:I am test message 0. MessageID:3EBE662B52BC99BC-1-154BD99CCA7-200000001
    Send Message Succeed! MessageBody:I am test message 1. MessageID:64B92941FC57837F-2-154BD99CCCE-200000001
    Send Message Succeed! MessageBody:I am test message 2. MessageID:3EBE662B52BC99BC-1-154BD99CCF0-200000002
  • 核心代码

    endpointaccidacckeytoken从步骤一的配置文件中读取。

    #init my_account, my_queue
    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    my_queue = my_account.get_queue(queue_name)
    
    #send some messages
    msg_count = 3
    
    print "%sSend Message To Queue%s\nQueueName:%s\nMessageCount:%s\n" % (10*"=", 10*"=", queue_name, msg_count)
    for i in range(msg_count):
        try:
            msg_body = "I am test message %s." % i
            msg = Message(msg_body)
            re_msg = my_queue.send_message(msg)
            print "Send Message Succeed! MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id)
        except MNSExceptionBase, e:
            if e.type == "QueueNotExist":
                print "Queue not exist, please create queue before send message."
                sys.exit(0)
            print "Send Message Fail! Exception:%s\n" % e      

步骤四:接收和删除消息

运行recvdelmessage.py,接收并删除队列中的消息,直到队列为空。如果步骤二指定了队列名称,这里同样通过参数指定队列名称。程序中receive message使用LongPolling方式,指定 wait seconds为3秒,因此当队列为空时,程序会等待3秒。消息详细信息请参考QueueMessage

  • 运行以下命令:
    $python recvdelmessage.py MyQueue1
    ==========Receive And Delete Message From Queue==========
    QueueName:MyQueue1
    WaitSeconds:3
    
    Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTEtOA== MessageBody:I am test message 0. MessageID:3EBE662B52BC99BC-1-154BD99CCA7-200000001
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTEtOA==
    Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5NC0xNDYzNDcwNDU4LTEtOA== MessageBody:I am test message 2. MessageID:3EBE662B52BC99BC-1-154BD99CCF0-200000002
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5NC0xNDYzNDcwNDU4LTEtOA==
    Receive Message Succeed! ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTItOA== MessageBody:I am test message 1. MessageID:64B92941FC57837F-2-154BD99CCCE-200000001
    Delete Message Succeed!  ReceiptHandle:1-ODU4OTkzNDU5My0xNDYzNDcwNDU4LTItOA==
    Queue is empty!
    					
  • 核心代码

    endpointaccidacckeytoken从步骤一的配置文件中读取。

    #init my_account, my_queue
    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    my_queue = my_account.get_queue(queue_name)
    
    
    #receive and delete message from queue util the queue is empty
    #set the long polling wait time 3 seoncds by wait_seconds
    
    wait_seconds = 3
    print "%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (10*"=", 10*"=", queue_name, wait_seconds)
    while True:
        #receive message
        try:
            recv_msg = my_queue.receive_message(wait_seconds)
            print "Receive Message Succeed! ReceiptHandle:%s MessageBody:%s MessageID:%s" % (recv_msg.receipt_handle, recv_msg.message_body, recv_msg.message_id)
        except MNSExceptionBase,e:
            if e.type == "QueueNotExist":
                print "Queue not exist, please create queue before receive message."
                sys.exit(0)
            elif e.type == "MessageNotExist":
                print "Queue is empty!"
                sys.exit(0)
            print "Receive Message Fail! Exception:%s\n" % e
            continue
    
        #delete message
        try:
            my_queue.delete_message(recv_msg.receipt_handle)
            print "Delete Message Succeed!  ReceiptHandle:%s" % recv_msg.receipt_handle
        except MNSException,e:
            print "Delete Message Fail! Exception:%s\n" % e         

步骤五:删除队列

运行deletequeue.py删除队列。

  • 运行以下命令:
    $python deletequeue.py MyQueue1
    Delete Queue Succeed! QueueName:MyQueue1       
  • 核心代码

    endpointaccidacckeytoken从步骤一的配置文件中读取。

    #init my_account, my_queue
    my_account = Account(endpoint, accid, acckey, token)
    queue_name = sys.argv[1] if len(sys.argv) > 1 else "MySampleQueue"
    my_queue = my_account.get_queue(queue_name)
    
    #delete queue
    try:
        my_queue.delete()
        print "Delete Queue Succeed! QueueName:%s\n" % queue_name
    except MNSExceptionBase, e:
        print "Delete Queue Fail! Exception:%s\n" % e