ACTIVEMQ Combat (ii)-code example

Source: Internet
Author: User
Tags diff sleep split qpid

The directory after ACTIVEMQ is extracted as follows:


Each directory is described as follows: Bin:activemq's startup script conf:activemq all profile data: Log file and persistent message DOCS:ACTIVEMQ official documentation EXAMPLES:ACTIVEMQ the official demo LIB:ACTIVEMQ Run the required library WEBAPPS:ACTIVEMQ Web console WEBAPPS-DEMO:ACTIVEMQ WebApps related demo ACTIVEMQ-ALL-5.13.2.JAR:ACTIVEMQ CLI jar Package for user system calls

Among them, examples is the official samples provided by ACTIVEMQ, and beginners can familiarize themselves with the use of ACTIVEMQ by studying these samples.

This article will implement a simple publish-subscribe example through ACTIVEMQ.

1, Producer

Package COM.RICKY.CODELAB.ACTIVEMQ.AMQP;
Import java.io.IOException;
Import java.util.Properties;
Import javax.jms.Connection;
Import Javax.jms.DeliveryMode;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.MessageProducer;
Import javax.jms.Session;
Import Javax.jms.TextMessage;
Import Org.apache.qpid.jms.JmsConnectionFactory;

Import Com.ricky.codelab.activemq.util.PropertyUtils;

    public class Producerdemo {private int messages = 10000;
        public static void Main (string[] args) {try {new Producerdemo (). publish ();
        } catch (JMSException e) {e.printstacktrace ();
        } catch (IOException e) {e.printstacktrace (); }} public void Publish () throws JMSException, ioexception{Properties props = propertyutils.load ("Activ

        Emq.properties ");

        String type = Props.getproperty ("Activemq.type", "topic:event"); String user = Props.getproperty ("Activemq.username", "admin ");
        String Password = props.getproperty ("Activemq.password", "password");

        String Server = Props.getproperty ("Activemq.server", "localhost:5672");

        String Connectionuri = "amqp://" + server;

        Jmsconnectionfactory factory = new Jmsconnectionfactory (Connectionuri);
        Connection Connection = factory.createconnection (user, password);

        Connection.start ();

        Session session = Connection.createsession (false, Session.auto_acknowledge);
        string[] arr = Type.split (":");
        Destination Destination = null;
        if (arr[0].equals ("topic")) {destination = Session.createtopic (Type.split (":") [1]);
        } else {destination = Session.createqueue (Type.split (":") [1]);
        } messageproducer producer = Session.createproducer (destination);

        Producer.setdeliverymode (deliverymode.non_persistent); for (int i = 1; i <= messages; i++) {TextMessage msg = Session.createtExtmessage ("#:" + i);
            Msg.setintproperty ("id", i);
            Producer.send (msg);
            if ((i) = = 0) {System.out.println (String.Format ("Sent%d messages", i));
        }} producer.send (Session.createtextmessage ("SHUTDOWN"));
        try {thread.sleep (1000 * 3);
        } catch (Interruptedexception e) {e.printstacktrace ();
    } connection.close ();
 }
}

2, Consumer

Package COM.RICKY.CODELAB.ACTIVEMQ.AMQP;
Import java.io.IOException;
Import java.util.Properties;
Import javax.jms.Connection;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageConsumer;
Import javax.jms.Session;
Import Javax.jms.TextMessage;
Import Org.apache.qpid.jms.JmsConnectionFactory;

Import Com.ricky.codelab.activemq.util.PropertyUtils; public class Consumerdemo {public static void main (string[] args) {try {new Consumerdemo (). su
        Bscribe ();
        } catch (IOException e) {e.printstacktrace ();
        } catch (JMSException e) {e.printstacktrace (); }} public void Subscribe () throws IOException, jmsexception{Properties props = propertyutils.load ("act

        Ivemq.properties ");

        String type = Props.getproperty ("Activemq.type", "topic:event");
        String user = Props.getproperty ("Activemq.username", "admin"); String Password = PRops.getproperty ("Activemq.password", "password");

        String Server = Props.getproperty ("Activemq.server", "localhost:5672");

        String Connectionuri = "amqp://" + server;

        Jmsconnectionfactory factory = new Jmsconnectionfactory (Connectionuri);
        Connection Connection = factory.createconnection (user, password);
        Connection.start ();

        Session session = Connection.createsession (false, Session.auto_acknowledge);

        string[] arr = Type.split (":");
        Destination Destination = null;
        if (arr[0].equals ("topic")) {destination = Session.createtopic (arr[1]);
        } else {destination = Session.createqueue (arr[1]);
        } Messageconsumer consumer = session.createconsumer (destination);
        Long start = System.currenttimemillis ();
        Long Count = 1;
        System.out.println ("Waiting for Messages ...");
            while (true) {Message msg = consumer.receive (); if (msg INstanceof textmessage) {String BODY = ((textmessage) msg). GetText ();
                    if ("SHUTDOWN". Equals (body)) {Long diff = system.currenttimemillis ()-Start;
                    System.out.println (String.Format ("Received%d in%.2f seconds", Count, (1.0 * diff/1000.0)));
                    Connection.close ();
                    try {thread.sleep (10);
                } catch (Exception e) {} system.exit (1);
                            } else {try {if (count! = Msg.getintproperty ("id")) {
                        System.out.println ("mismatch:" + count + "! =" + msg.getintproperty ("id")); }} catch (NumberFormatException ignore) {} if (count = = 1)
                    {start = System.currenttimemillis ();
              } else if (count% 1000 = = 0) {          System.out.println (String.Format ("Received%d messages.", count));
                } count++;
            }} else {System.out.println ("unexpected message type:" + msg.getclass ());
 }
        }
    }
}

Click here to download the complete code.


Resources:
Https://activemq.apache.org/initial-configuration.html
Http://activemq.apache.org/examples.html

Related Article

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.