ACTIVEMQ Message Queuing-single node test (point-to-point mode)

Source: Internet
Author: User

ACTIVEMQ the process of sending and receiving messages is similar to the JDBC Operations database: First create the Connection connection object, then the session object, and then create producer, Consumer, Objects such as message, except that ACTIVEMQ connection objects are generated through the Activemqconnectionfactory factory. Here are the test code for some scenarios.

Define some constant data, which is also useful in the following example

User name private final static string USERNAME = activemqconnection.default_user;//Password private final static string PASSWORD = A ctivemqconnection.default_password;//node Urlprivate final static String Brokerurl = "tcp://localhost:61616";// Queue name Private final static String DESTINATION = "Com_mq_queue_test";

1, first test the simplest of this, is the message sender sends a message, and then the receiver receives the message, and the message is received by the consumer, the use of automatic response mode (Session.auto_acknowledge), feedback to the message sent.

Sender Code: @Testpublic  void run ()  {    try {//  Create Activemqconnectionfactory Factory Connectionfactory factory = new activemqconnectionfactory ( Username, password, brokerurl);//  Create connection objects through the Activemqconnectionfactory factory connection  Connection = factory.createconnection ();//  Start Connection Object Connection.start ();//  Create Session Sessions Session session = connection.createsession (False, session.auto_acknowledge);D Estination destination = session.createqueue (destination); Messageproducer sender = session.createproducer (destination);//  sets the persistence mode for messages: If set to persistent, The message is delivered when it is stored and then passed. That is, message->broker->message store-> returns to the message sender whether the message is stored successfully//  if set to non-persisted, indicating that the message is asynchronous delivery, The delivery path of the message is the 2 steps that message-broker-> returns to the sender of the message and stores the data asynchronously, the performance is faster than the persistence mode// deliverymode not set or set to Non_persistent, Then the message will be lost after restarting MQ; Persistent guarantees that the unsent data will be sent again until the transmission is successful         Sender.setdeliverymode (deliverymode.non_persistent);//  Create a message and send a message message message =  Session.createmessage (); Message.setstringproperty ("Name",  "Tom"); sender.send (message);//  Close resource Session.close ();         connection.close ();     } catch (exception e)  {e.printstacktrace ();    }}//  Receiver code: @Testpublic  void run ()  {    try {connectionfactory factory  = new activemqconnectionfactory (Username, password, brokerurl); Connection connection = factory.createconnection (); Connection.start (); Session session = connection.createsession (False, session.auto_acknowledge);D estination  destination = session.createqueue (destination); Messageconsumer receiver = session.createconsumer (destination); Message message = receiver.receive (); String naMe = message.getstringproperty ("name"); System.out.println ("Received message body is:"  + name);// message.acknowledge ();   session.auto_ Acknowledge, the default automatically sends a confirmation message receiver.close ();         session.close ();         connection.close ();     } catch (Exception  e)  {e.printstacktrace ();     }}

When creating a session, Connection.createsession (Boolean istranscration, int acknowledge), the first parameter indicates whether the transaction is used, and the second parameter represents the pattern of the message reply in use.

Why do you have these 2 parameters? My personal understanding is this, first of all, we all know that the transaction is simply to ensure that a batch of operations either all succeed, or all fail, there is no partial success, partial failure. In ACTIVEMQ, message sending can also send multiple message messages in a session, but to ensure that multiple messages are in one transaction, you need to set Istranscration to True, and after setting, you need to call Session.commit () commits the transaction.

The acknowledge parameter represents the mode of message answering, the message is sent out, the receiver receives the message, it needs feedback to the sender, and then the message is removed from the queue. the value of acknowledge is Auto_acknowledge, Client_acknowledge, Dups_ok_acknowledge three kinds. Auto_acknowledge represents the automatic answer mode, after the message consumer receives the message, it automatically answers to the sending send,Client_acknowledge indicates that the message consumer sends the reply notification, after the consumer receives the message, You need to call the acknowledge () method of message, otherwise the queue will not remove the message, which could result in garbage data. The specific response code is as follows:

Message message = Receiver.receive (); String name = Message.getstringproperty ("name"); System.out.println ("Received message body is:" + name);//Message Acknowledgement: Otherwise the data will not be deleted Message.acknowledge ();

2. Test the same transaction (only focus on message sender)

@Testpublic  void testtranscation ()  {    try {ConnectionFactory  Factory = new activemqconnectionfactory (Username, password, brokerurl); Connection connection = factory.createconnection (); Connection.start ();//   with transaction session  session = connection.createsession (True, session.auto_acknowledge);D estination  Destination = session.createqueue (destination); Messageproducer sender = session.createproducer (destination); Sender.setdeliverymode ( deliverymode.non_persistent);//  send multiple messages for (int i = 0; i < 10; i++)  {    message message = session.createmessage ();     message.setstringproperty ("name_"  + i,  "Yangyong_"  + i);     sender.send (message);     if (i == 1)  { //  Analog Exception Int count = 10 / 0;    }}//  needs to call the Commit method Session.commit (); session.close ();         connection.close ();     } catch ( exception e)  {e.printstacktrace ();     }}

The code uses a 10/0 simulation exception, and the test results indicate that 10 messages were not sent to the queue.

3. Using the database to store messages

If you want to persist the message to the database, you only need to modify the Activemq.xml file to test the code and store the data in the same way as the file. First, add the following configuration on the <broker/> tab of the Activemq.xml file (for MySQL, for example, manually build the database)

<bean id= "Mysql-ds" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "close" > <property name = "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql://localhost/ Activemq?relaxautocommit=true "/> <property name=" username "value=" root "/> <property name=" password "Valu e= "root"/> <property name= "maxactive" value= "$"/> <property name= "poolpreparedstatements" value= "true" /></bean>

Then find the <persistenceadapter/> tag in <broker/>, comment out the configuration, and replace it with the following configuration

<persistenceAdapter> <jdbcpersistenceadapter datasource= "#mysql-ds" Createtableson Startup= "true" usedatabaselock= "false"/></persistenceadapter>

4. Message Filtering (selector)

ACTIVEMQ is a message bus, messages in multiple applications can be sent to a queue, each application's message consumer may only focus on the message generated by the system, you need to define a selector, filter out the message data of interest through the attribute value. Selector can support a variety of expressions, such as =,>,<, and so on, you can refer to the "ActiveMQ in Action" book.

  Test selector message filtering: Sender @testpublic void testselector ()  {    try { Connectionfactory factory = new activemqconnectionfactory (USERNAME, PASSWORD,  Brokerurl); Connection connection = factory.createconnection (); Connection.start (); Session session = connection.createsession (True, session.auto_acknowledge);D estination  destination = session.createqueue (destination); Messageproducer sender = session.createproducer (destination); Sender.setdeliverymode ( deliverymode.non_persistent);//Send 2 messages  textmessage message = session.createtextmessage (" Test selector Message Filter 1 "), Message.setstringproperty (" from ", " Jack "); sender.send (message);message =  Session.createtextmessage ("Test selector message Filter 2"), Message.setstringproperty ("from",  "Tom"); Sender.send (Message ); Session.commit (); Session.close ();         connection.cloSe ();     } catch (exception e)  {e.printstacktrace ();     }}//  Test Selector message filtering: Consumer @testpublic void testselector ()  {    try { Connectionfactory factory = new activemqconnectionfactory (USERNAME, PASSWORD,  Brokerurl); Connection connection = factory.createconnection (); Connection.start (); Session session = connection.createsession (False, session.auto_acknowledge);D estination  destination = session.createqueue (destination);//  set filter Criteria string selector =  "From= ' Jack '";//  create a Messageconsumer object with filter criteria messageconsumer consumer =  Session.createconsumer (Destination, selector); textmessage message =  (TextMessage)  consumer.receive (); System.out.println ("received message:"  + message.gettext ()); Session.close ();         connection.close ();    } catch (exception e)  {e.printstacktrace ();     }} 

The test results indicate that the message consumer can only receive the first message sent out, and the second from= ' Tom ' message cannot be received.

5, after the consumer receives the message, sends the message to the message sender

After the message is received by the consumer, it may be necessary for the consumer to feed the results back to the sender, and then the issuing party executes some business logic, the process of which is

  Message Send public class queuesender {    public void  Testreplyto ()  {        try {    Connectionfactory factory = new activemqconnectionfactory (USERNAME, PASSWORD,  Brokerurl);     final connection connection = factory.createconnection ( );     connection.start ();     final session session =  connection.createsession (False, session.auto_acknowledge);    destination  Destination = session.createqueue (destination);     messageproducer sender  = session.createproducer (destination);     sender.setdeliverymode ( Deliverymode.non_persistent);    textmessage message =  Session.createtextmessage ("Test message consumer returns processing result to message producer");     seNder.send (message);    //  accept messages returned by consumer     MessageConsumer  Consumer = session.createconsumer (destination);     consumer.setmessagelistener ( New messagelistener ()  {        public void  OnMessage (message message)  {    if (message != null &&  message instanceof textmessage)  {try {    system.out.println (" Message Consumer feedback information->messageid: "                  + message.getjmscorrelationid ()  +  ", message entity:"                   +  ((textmessage) message). GetText ( ));     //Close Resource     session.close ();            &nbsP;connection.close ();        } catch  (JMSException e)  {    e.printstacktrace ();}     }}    });        }  catch (Exception e)  {    e.printstacktrace ();         }   }   public static void main (String[] args)  {new queuesender (). Testreplyto ();    } }  //   message receiver:  public class  QueueReceiver {     public void  Testreplyto ()  {        try {    Connectionfactory factory = new activemqconnectionfactory (USERNAME, PASSWORD,  Brokerurl);     final connection connection = factory.crEateconnection ();     connection.start ();    final session  Session = connection.createsession (False, session.auto_acknowledge);     Final destination destination = session.createqueue (Destination);     Messageconsumer consumer = session.createconsumer (destination);     Consumer.setmessagelistener (New messagelistener ()  {         Public void onmessage (message message)  {    if (message !=  Null && message instanceof textmessage)  {         try {    system.out.println ("Received message->messageid:"                   +  Message.getjmsmessageid ()  +  ", message entity:"                 +  (( TextMessage). GetText ());    //  send message to message producer      Messageproducer sender = session.createproducer (destination);     Sender.setdeliverymode (deliverymode.non_persistent);     textmessage message0 =  session.createtextmessage ("The consumer has processed the message you sent");//  must set these parameters Jmscorrelationid: The ID of the received message, Jmsreplyto: Message sent to this address     message0.setjmscorrelationid (Message.getjmsmessageid ());     message0.setjmsreplyto (destination);     sender.send (MESSAGE0);     session.close ();             Connection.close ();}  catch  (jmsexception e)  {    e.printstacktrace ();}     }}    });        } catch (exception e)  {    e.printstacktrace () ;}     }    public static void main (String[] args)  {new queuereceiver (). Testreplyto ();     }}


ACTIVEMQ Message Queuing-single node test (point-to-point mode)

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.