队列使用手册

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

步骤一:准备工作

  1. 下载最新版Python SDK,解压后进入mns_python_sdk子目录。

  2. 打开sample.cfg文件,配置AccessKeyId、AccessKeySecret、Endpoint和SecurityToken。

    • AccessKeyId、AccessKeySecret

    • Endpoint

      • 访问消息服务MNS的接入地址,登录MNS控制台查看。具体操作,请参见获取接入点

      • 不同地域的接入地址不同。

    • SecurityToken

      • 阿里云访问控制服务提供的短期访问权限凭证,如果使用阿里云账号或者RAM用户访问,不需要配置该项。更多信息,请参见什么是STS

  3. 进入sample目录,后续使用的脚本都在该目录。

步骤二:创建队列

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

  • 运行以下命令:

    python createqueue.py MyQueue1         

    返回结果如下:

    Create Queue Succeed! QueueName:MyQueue1
  • 核心代码:

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

    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)
    
    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从步骤一配置的sample.cfg文件中读取。

    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)
    
    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方式,指定WaitSeconds为3秒,因此当队列为空时,程序会等待3秒。更多信息,请参见QueueMessage

说明

如果运行代码时报错:SyntaxError: encoding problem: utf8,请切换CRLF后再次尝试。

  • 运行以下命令:

    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从步骤一配置的sample.cfg文件中读取。

    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)
    
    wait_seconds = 3
    print "%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (10*"=", 10*"=", queue_name, wait_seconds)
    while True:
        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
    
        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从步骤一配置的sample.cfg文件中读取。

    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)
    
    try:
        my_queue.delete()
        print "Delete Queue Succeed! QueueName:%s\n" % queue_name
    except MNSExceptionBase, e:
        print "Delete Queue Fail! Exception:%s\n" % e