On the implementation of MNS message sending and receiving __mns

Source: Internet
Author: User
Tags message queue aliyun

When I use MNS to send a message, I use the Aliyun MNS. Most of the problems are found in official documents.

The messaging service MNS provides two API interfaces, one is the queue interface and the other is the subject interface.

The queue interface is suitable for point-to-point messaging, and when receiving messages, the application-side polling is required to obtain the message (pull mode).

The theme interface is suitable for a one-to-many message transceiver, the application end only need to start listening on an address, the server will actively push the message past (push mode). 1, in fact, use both ways have their own advantages and disadvantages, or provide two kinds of ways there is no difference.

2, the queue model guarantees that messages will be consumed at least once, supporting multiple producers and consumers to operate the same message queue concurrently. When consuming messages, try to be as advanced as possible, precisely because some of the features of distributed Message Queuing do not guarantee that you will be able to consume messages in the order in which they are sent, and if your business needs to be advanced first, it is recommended that you add ordinal information to the message to reorder the messages.

3, the theme model supports the service-side initiative to push messages to the user-specified callback address (Endpoint), eliminating unnecessary polling and resource consumption for user programs.
The theme model guarantees that the notification message is pushed to the user in accordance with the specified policy and that multiple message publishers concurrently operate the same topic. The theme mode supports a One-to-many broadcast message, and a notification message can be received and consumed by multiple subscribers at the same time.

My main point here is the implementation method:

First, the queue interface

1. Create queues

public class Createqueuedemo {public static void main (string[] args) {cloudaccount account = new Cloudaccoun
        T ("Youraccessid", "Youraccesskey", "Mnsendpoint"); Mnsclient client = Account.getmnsclient ();
        In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security String queuename = "Testqueue"; Queuemeta meta = new Queuemeta ();  Generate local Queuemeta properties, about queue properties See https://help.aliyun.com/document_detail/27476.html meta.setqueuename (queuename) in detail;
        Set queue name Meta.setpollingwaitseconds (15);
        Meta.setmaxmessagesize (2048L);
        try {cloudqueue queue = client.createqueue (meta);  catch (clientexception CE) {System.out.println ("something Wrong with" network connection
                   Client and MNS service. "
            + "Please check your network and DNS availablity.");
        Ce.printstacktrace ();
            catch (Serviceexception se) {se.printstacktrace (); Logger.error ("MNS exception RequestID: "+ se.getrequestid (), SE);
                    if (Se.geterrorcode ()!= null) {if (Se.geterrorcode (). Equals ("Queuenotexist")) { System.out.println ("Queue is not exist.")
                Please create a before use "); else if (Se.geterrorcode (). Equals ("timeexpired")) {System.out.println ("the request is time expired.
                Please check the your local Machine Timeclock "); }/* You can get more MNS service error code from following Link:https://help.aliyun. com/document_detail/mns/api_reference/error_code/error_code.html */} catch (Exception E
            ) {System.out.println ("Unknown exception happened!");
        E.printstacktrace ();  } client.close (); When the program exits, the client's Close method needs to be actively invoked for resource release}}

Of course, you must have the relevant key, parameters, and keys provided by Aliyun.

2. Send Message

public class Producerdemo {public static void main (string[] args) {cloudaccount account = new Cloudaccount ("
        Youraccessid "," Youraccesskey "," Mnsendpoint "); Mnsclient client = Account.getmnsclient ();
            In the program, Cloudaccount and Mnsclient can be implemented in a single instance, multithreading security try {cloudqueue queue = Client.getqueueref ("Testqueue");
            Message message = new Message ();
            Message.setmessagebody ("I AM Test Message");
            Message putmsg = queue.putmessage (message);
        SYSTEM.OUT.PRINTLN ("Send Message ID is:" + Putmsg.getmessageid ());  catch (clientexception CE) {System.out.println ("something Wrong with" network connection
                   Client and MNS service. "
            + "Please check your network and DNS availablity.");
        Ce.printstacktrace ();
            catch (Serviceexception se) {se.printstacktrace (); Logger.error ("MNS exception RequestID:" + Se.getrequestid (), Se);
                    if (Se.geterrorcode ()!= null) {if (Se.geterrorcode (). Equals ("Queuenotexist")) { System.out.println ("Queue is not exist.")
                Please create a before use "); else if (Se.geterrorcode (). Equals ("timeexpired")) {System.out.println ("the request is time expired.
                Please check the your local Machine Timeclock "); }/* You can get more MNS service error code from following Link:https://help.aliyun. com/document_detail/mns/api_reference/error_code/error_code.html */} catch (Exception E
            ) {System.out.println ("Unknown exception happened!");
        E.printstacktrace ();  } client.close (); When the program exits, the client's Close method needs to be actively invoked for resource release}}


3. Accept and DELETE messages

public class Consumerdemo {public static void main (string[] args) {cloudaccount account = new Cloudaccount ("
        Youraccessid "," Youraccesskey "," Mnsendpoint "); Mnsclient client = Account.getmnsclient ();
            In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security try{cloudqueue queue = Client.getqueueref ("Testqueue");
            Message popmsg = Queue.popmessage ();
                if (popmsg!= null) {SYSTEM.OUT.PRINTLN ("message handle:" + popmsg.getreceipthandle ());
                SYSTEM.OUT.PRINTLN ("message body:" + popmsg.getmessagebodyasstring ());
                SYSTEM.OUT.PRINTLN ("Message ID:" + popmsg.getmessageid ());
                SYSTEM.OUT.PRINTLN ("Message dequeue count:" + popmsg.getdequeuecount ());
                    Delete messages that have been taken out of consumption queue.deletemessage (Popmsg.getreceipthandle ());
            System.out.println ("delete message successfully.\n"); } else{System.out.println ("MeSsage not exist in testqueue.\n "); The catch (clientexception CE) {System.out.println ("something wrong with the network Connecti
                    On between client and MNS service. "
            + "Please check your network and DNS availablity.");
        Ce.printstacktrace ();
            catch (Serviceexception se) {se.printstacktrace ();
            Logger.error ("MNS exception RequestID:" + se.getrequestid (), SE);
                    if (Se.geterrorcode ()!= null) {if (Se.geterrorcode (). Equals ("Queuenotexist")) { System.out.println ("Queue is not exist.")
                Please create a before use "); else if (Se.geterrorcode (). Equals ("timeexpired")) {System.out.println ("the request is time expired.
                Please check the your local Machine Timeclock ");
         }/* You can get more MNS service error code from following link:   https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html */}
            catch (Exception e) {System.out.println ("Unknown Exception happened!");
        E.printstacktrace ();
    } client.close (); }
}


4. Delete queues

public class Deletequeuedemo {public
    static void Main (string[] args) {
        cloudaccount account = new Cloudaccount ("Y Ouraccessid "," Youraccesskey "," Mnsendpoint ");
        Mnsclient client = Account.getmnsclient (); In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security
        try{
            cloudqueue queue = Client.getqueueref ("Testqueue");
            Queue.delete ();
        } catch (clientexception CE)
        {
            System.out.println ("Something Wrong with" network connection client and M NS service. "
                    + "Please check your network and DNS availablity.");
            Ce.printstacktrace ();
        } catch (serviceexception se)
        {
            se.printstacktrace ();
        } catch (Exception e)
        {
            System.out.println ("Unknown exception happened!");
            E.printstacktrace ();
        }
        Client.close ();
    }


II. Thematic approach

1. Create a Theme

public class Createtopicdemo {public
    static void Main (string[] args) {
        cloudaccount account = new Cloudaccount ("Y Ouraccessid "," Youraccesskey "," Mnsendpoint ");
        Mnsclient client = Account.getmnsclient (); In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security
        String topicname = "Testtopic";
        Topicmeta meta = new Topicmeta ();
        Meta.settopicname (topicname);
        try {
            Cloudtopic topic = client.createtopic (meta);
        } catch (Exception e)
            e.printstacktrace ();
            SYSTEM.OUT.PRINTLN ("Create topic error," + e.getmessage ());
        }
        Client.close ();
    }


2. Send Message

public class Publishmessagedemo {public
    static void Main (string[] args) {
        cloudaccount account = new Cloudaccount ("Youraccessid", "Youraccesskey", "Mnsendpoint");
        Mnsclient client = Account.getmnsclient (); In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security
        cloudtopic topic = Client.gettopicref ("Testtopic");
        try {
            topicmessage msg = new Base64topicmessage ();//You can use the Topicmessage structure to choose not to Base64 encrypt
            msg.setmessagebody (" Hello world! ");
            Msg.setmessagetag ("Filtertag"); Sets the Filtertag
            msg = topic.publishmessage (msg) for which the article publishes a message;
            System.out.println (Msg.getmessageid ());
            System.out.println (MSG.GETMESSAGEBODYMD5 ());
        } catch (Exception e) {
            e.printstacktrace ();
            SYSTEM.OUT.PRINTLN ("subscribe error");
        }
        Client.close ();
    }


3. Create subscriptions, accept messages

public class Consumerdemo {    public static void main (string[] args) {        Cloudaccoun
T account = new Cloudaccount ("Youraccessid", "Youraccesskey", "Mnsendpoint");         Mnsclient client = Account.getmnsclient (); In the program, Cloudaccount and mnsclient single example implementation, multithreading security         try{            Clo
Udtopic topic = Client.gettopicref ("Testtopic");
            Ubscriptionmeta Submeta = new Subscriptionmeta ();
            Submeta.setsubscriptionname ("TestSub");             Submeta.setnotifycontentformat (
SubscriptionMeta.NotifyContentFormat.SIMPLIFIED);             Submeta.setendpoint (Topic.generatequeueendpoint ("Testqueue");     & nbsp
      Submeta.setfiltertag ("Filtertag");
            Topic.subscribe (Submeta);            //Subscribe Related Topics             Cloudqueue queue = Client.getqueueref ("Test
Queue ");
            Message popmsg = Queue.popmessage ();             if (popmsg!= null) {                Sys
TEM.OUT.PRINTLN ("message handle:" + popmsg.getreceipthandle ());                 SYSTEM.OUT.PRINTLN ("message body:" + Popmsg.getmessagebodyasstrin
g ());
                SYSTEM.OUT.PRINTLN ("Message ID:" + popmsg.getmessageid ());                 SYSTEM.OUT.PRINTLN ("Message dequeue count:" + Popmsg.getdequeuecou
NT ());                //delete messages that have been taken out of consumption               &NB Sp
 queue.deletemessage (Popmsg.getreceipthandle ());                     SYSTEM.OUT.PRINTLN ("delete message successfully.\n");                         else{        &N Bsp
      SYSTEM.OUT.PRINTLN ("exist in testqueue.\n");             {       } catch (clientexception CE)          {            SYSTEM.OUT.PRINTLN ("Something wrong with the network connection between Client and MNS service. "                    +" Please check your netwo
RK and DNS availablity. ");
            ce.printstacktrace ();         } catch (Serviceexception se)         {         
  Se.printstacktrace ();
            Logger.error ("MNS exception RequestID:" + se.getrequestid (), SE); &nBsp           if (Se.geterrorcode ()!= null) {              &NBSP ; if (Se.geterrorcode (). Equals ("Queuenotexist"))                 {    &NB Sp               SYSTEM.OUT.PRINTLN ("Queue is not exist.")
Please create a before use ");                 else if (Se.geterrorcode (). Equals ("timeexpired"))                 {                    SYSTEM.O UT.PRINTLN ("The request is time expired.")
Please check the your local Machine Timeclock ");                            /    &NBSP ;       can get more MNS service error code from following link:           &NBSP ; Https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html            /           }         } catch (Exception e)         {           
System.out.println ("Unknown exception happened!");
            e.printstacktrace ();
       }         client.close ();
    }}
4. Unsubscribe, delete Zhu ' t

The queue model guarantees that messages will be consumed at least once, supporting multiple producers and consumers to operate the same message queue concurrently.

When consuming messages, try to get ahead first, precisely because some of the features of distributed Message Queuing do not guarantee that you can follow the message

Sequential consumption messages, if your business must be advanced first out, it is recommended to add ordinal information in the message to the consumer message after the rearrangement

Order.

The queue model guarantees that messages will be consumed at least once, supporting multiple producers and consumers to operate the same message queue concurrently.

When consuming messages, try to get ahead first, precisely because some of the features of distributed Message Queuing do not guarantee that you can follow the message

Sequential consumption messages, if your business must be advanced first out, it is recommended to add ordinal information in the message to the consumer message after the rearrangement

Order.

The queue model guarantees that messages will be consumed at least once, supporting multiple producers and consumers to operate the same message queue concurrently.

When consuming messages, try to get ahead first, precisely because some of the features of distributed Message Queuing do not guarantee that you can follow the message

Sequential consumption messages, if your business must be advanced first out, it is recommended to add ordinal information in the message to the consumer message after the rearrangement

Order.

The queue model guarantees that messages will be consumed at least once, supporting multiple producers and consumers to operate the same message queue concurrently.

When consuming messages, try to get ahead first, precisely because some of the features of distributed Message Queuing do not guarantee that you can follow the message

Sequential consumption messages, if your business must be advanced first out, it is recommended to add ordinal information in the message to the consumer message after the rearrangement

Order.

public class Deletetopicdemo {public
    static void Main (string[] args) {
        cloudaccount account = new Cloudaccount ("Y Ouraccessid "," Youraccesskey "," Mnsendpoint ");
        Mnsclient client = Account.getmnsclient (); In the program, Cloudaccount and Mnsclient can be implemented in single instance, multithreading security
        cloudtopic topic = Client.gettopicref ("Testtopic");
        try {
            topic.unsubscribe ("TestSub");
            Topic.delete ();
        } catch (Exception e) {
            e.printstacktrace ();
            System.out.println ("Delete topic error");
        }
        Client.close ();
    }

This is almost the official website of the case.

But as long as in accordance with this order and the idea of writing will not be a problem.

Use the injection method more often when you are using spring.

So with this in mind, half will write the configuration information of these things in XML. Such as

    <bean id= "Queuemeta" class= "Com.aliyun.mns.model.QueueMeta" >
        <property name= "QueueName" value= "${" QueueName} "/>
        <property name= pollingwaitseconds" value= "/> <property" name=
        "Value=" 2048 "/>
    </bean>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.