Code records for ACTIVEMQ through Java operations

Source: Internet
Author: User

ACTIVEMQ Data-Sending class


import javax.jms.deliverymode;import javax.jms.destination;import javax.jms.messageproducer; import javax.jms.session;import javax.jms.textmessage;import  Org.apache.activemq.activemqconnectionfactory;import org.apache.activemq.pool.pooledconnection;import  org.apache.activemq.pool.PooledConnectionFactory;public class ActiveMQSend {     private final string ip;    private final string  port;    private PooledConnection pooledConnection;     /**     *  Construction methods (incoming IP and ports that need to be connected)      *      *  @param  ip  (avctivemq service IP)      *  @param   port  (ACTIVEMQ service port)      */    public activemqsend ( String ip, string port)  {        this.ip = ip;        this.port  = port;        this.init ();    }     /**     *  initializing the ACTIVEMQ connection pool      */     private void init ()  {        try  {            String[] ips =  This.ip.split (",");             string[] ports  = this.port.split (",");             Stringbuilder tcplink = new stringbuilder ();             for  (int i = 0; i < ips.length; i++)  {                tcplink.append ("tcp://"). Append (Ips[i] ). Append (":"). Append (Ports[i]). Append (",");             }            String mqLink =  Tcplink.tostring ();            if  ( Tcplink.length ()  > 0)  {                 if  (', '  == tcplink.charat (Tcplink.length ()  - 1)  {                      mqlink = tcplink.substring (0, tcplink.length ()  - 1);                 }             }            string url =  string.format ("Failover: (%s)?" Initialreconnectdelay=1000&timeout=3000&startupmaxreconnectattempts =2 ",  mqlink);             Activemqconnectionfactory factory = new activemqconnectionfactory (URL);             factory.setmaxthreadpoolsize (;   )          pooledconnectionfactory poolfactory = new  pooledconnectionfactory (Factory);             pooledConnection =  (pooledconnection)  poolfactory.createconnection ();             pooledconnection.start ();         } catch  (exception&NBSP;EX)  {            logutil.error (ex);             this.destroy ();         }    }    /**      *  send data to ACTIVEMQ      *     *  @param   needsendmsg  The data information that needs to be sent      *  @param  sendMQName  queue name to send       */    public void send (String needSendMsg,  String sendmqname)  {        if  (this.pooledconnection  == null)  {            this.init ();         }        if  ( This.pooledconnection != nulL)  {            try {                 session session =  this.pooledconnection.createsession (Boolean.false, session.auto_acknowledge);                 destination destination  = session.createqueue (Sendmqname);                 messageproducer producer = session.createproducer ( Destination);                 Producer.setdeliverymode (deliverymode.persistent);                 textmessage message = session.createtextmessage (NEEDSENDMSG );       &Nbsp;         producer.send (message);                 session.close ();             } catch  (Exception ex)  {                 logutil.error (ex);                 this.destroy ();             }         }    }    /**     *  Recycling Connection Pools      */    public void destroy ()  {         try {             if  (pooledconnection != null)  {                 pooledconnection.stop ();             }         } catch  (exception e)  {             logutil.error (e);         }        try {             if  (pooledconnection != null)  {                 pooledconnection.close ();             }         } catch  (exception e)  {             logutil.error (e);        }         pooledconnection = null;    }}


Call Send

Public static void main (String[] args)  {         thread t1 = new thread (new runnable ()  {              @Override              public void run ()  {                 activemqsend sen = new activemqsend ("127.0.0.1",   "61616");                 for  (int i = 0; i < 50000; i++)  {                     string  msg = string.format ("This is the data sent by testqueue 2   %s ! ",  i);          &Nbsp;          sen.send (msg,  "TestQueue2");                 }             }        });         thread t2 = new thread (new Runnable ()   {             @Override              public void run ()  {                 activemqsend sen = new  activemqsend ("127.0.0.1",  "61616");                 for  (int i = 0; i < 50000; i++)  {   &nbSp;                string  msg = string.format ("This is the data sent by testqueue 1   %s ! ",  i);                     sen.send (msg,  "TestQueue1");                 }             }        });         t1.start ();         t2.start ();     }


ACTIVEMQ Data Reception Class

Import javax.jms.messageconsumer;import javax.jms.destination;import javax.jms.session;import  javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnectionFactory;import  Org.apache.activemq.pool.pooledconnection;import org.apache.activemq.pool.pooledconnectionfactory;public  class Receiver {    private PooledConnection pooledConnection;     private void init ()  {         try {            string url =  "Failover: (tcp://192.168.10.219:61616)?initialreconnectdelay=1000&timeout=3000& startupmaxreconnectattempts=2 ";             Activemqconnectionfactory factory = new activemqconnectionfactory (URL);             factorY.setmaxthreadpoolsize (;            ) Pooledconnectionfactory poolfactory = new pooledconnectionfactory (Factory);             pooledConnection =  (pooledconnection)  poolfactory.createconnection ();             Pooledconnection.start ();        } catch  (Exception ex)  {            log.error (ex);             this.destroy ();         }    }    public void receive (String  QueueName)  {        if  (this.pooledconnection ==  NULL) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;       this.init ();         }         if  (this.pooledconnection != null)  {             try {                 Session session =  This.pooledConnection.createSession (Boolean.false, session.auto_acknowledge);                 destination destination =  session.createqueue (queuename);                 messageconsumer consumer = session.createconsumer (destination);                 while  (True)  {     &nbsP;              textmessage message  =  (TextMessage)  consumer.receive (Ten);                     if  (null != message)  {                          system.out.println ("Received message"  + message.gettext ());                     }                 }             } catch  (Exception ex)  {                 log.info ( Ex.getmessage ());                this.destroy ();             }        }     }    public void destroy ()  {         try {             if  (pooledconnection != null)  {                 pooledconnection.stop ();             }        } catch  ( Exception e)  {            log.error (e);         }        try {             if  (pooledconnection != null)  {                 pooledconnection.close ();             }        }  catch  (exception e)  {             log.error (e);        }         pooledconnection = null;    }}


Invocation of the data receive class

Public static void main (String[] args)  {         thread t1 = new thread (new runnable ()  {              @Override              public void run ()  {                 receiver r1 = new receiver ();                 r1.receive ("TestQueue2");             }         });         thread t2 = new thread (new  Runnable ()  {             @Override         &Nbsp;    public void run ()  {                 receiver r2 = new receiver ();                 r2.receive (" TestQueue1 ");            }         });         t1.start ();         t2.start ();     }


Code records for ACTIVEMQ through Java operations

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.