ACTIVEMQ Installation and use

Source: Internet
Author: User
Tags constructor gettext message queue xmlns log4j

Always want to summarize the message queue, just recently have time, just fiddling with a bit. preparatory work Download

First go to ACTIVEMQ website to download the application. Select the corresponding version and download the extract.
Then you can use the version of Windows that I downloaded this time. Start

Use CMD to enter the Apache-activemq-5.14.3\bin directory. Then run the ACTIVEMQ Start program to start. The program's console page access port is 8161. Enter the http://localhost:8161/admin/ Queues.jsp can see which queues are now available. The app's access port defaults to 61616. Queue Operations send messages

Package activemq;
Import org.apache.activemq.ActiveMQConnection;

Import Org.apache.activemq.ActiveMQConnectionFactory;

Import javax.jms.*;
 /** * Created on 2017/1/24.

    */public class Sender {private static final int send_number = 5;

        public static void Main (String[]args) {connectionfactory connectionfactory;

        Connection Connection = null;

        Session session;

        Destination Destination;

        MessageProducer producer; ConnectionFactory = new Activemqconnectionfactory (Activemqconnection.default_user, Activemqconnection.defa

        Ult_password, "tcp://localhost:61616");

            try {connection = connectionfactory.createconnection ();

            Connection.start ();

            Session = Connection.createsession (Boolean.true,session.auto_acknowledge);

            Destination = Session.createqueue ("Send2recv");

         Producer = Session.createproducer (destination);   Producer.setdeliverymode (deliverymode.non_persistent);


            TextMessage message = Session.createtextmessage ("This is Message");
            Producer.send (message);

            System.out.println (Message.gettext ());

        Session.commit ();
        } catch (JMSException e) {e.printstacktrace (); }finally {try {if (null!= connection) Connection.clos
            E ();
            } catch (JMSException e) {e.printstacktrace ();
 }



        }
    }



}
Receive Message
Package activemq;
Import org.apache.activemq.ActiveMQConnection;


Import Org.apache.activemq.ActiveMQConnectionFactory;

Import javax.jms.*;
 /** * Created on 2017/1/24.

        */public class Receiver {public static void main (String args[]) {connectionfactory connectionfactory;

        Connection Connection = null;

        Session session;

        Destination Destination;

        Messageconsumer consumer; ConnectionFactory = new Activemqconnectionfactory (Activemqconnection.default_user, Activemqconnection.defa

        Ult_password, "tcp://localhost:61616");

            try {connection = connectionfactory.createconnection ();

            Connection.start ();

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

            Destination = Session.createqueue ("Send2recv");

            Consumer = session.createconsumer (destination);
        while (true) {        TextMessage message = (textmessage) consumer.receive ();
                if (null!=message) {System.out.println ("Receive Message" +message.gettext ());
                } else {break;
        }}} catch (JMSException e) {e.printstacktrace (); } finally {try {if (null!=connection) Connection.clo
            SE ();
            } catch (JMSException e) {e.printstacktrace ();

 }
        }
    }
}
integration with spring projects

In the official tutorial, just let the introduction of a Activemq-all jar package on it. After the introduction of the program has not been able to get up. Said slf2j bound two, because the version is not the same as the conflict. The original in the Activemq-all package of Pom file, He has included many of the jars he needs to use. It is useless to use exclusion, finally, instead, use the following dependency, solve.

   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms< /artifactid>
      <version>${spring.version}</version>
    </dependency>
    < dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactid>activemq-spring </artifactId>
      <version>5.10.0</version>
    </dependency>

Then there is the spring configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs
       I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:jms= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/ Context Http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/ JMS http://www.springframework.org/schema/jms/spring-jms.xsd "> <!--let JMS annotations take effect, this must be noted--<jms:annotati on-driven/> <bean id= "jmsfactory" class= "Org.apache.activemq.ActiveMQConnectionFactory" > <construc Tor-arg index= "0" value= "tcp://localhost:61616"/> </bean> <!--pooled Spring connection Factory--&gt
    ; <bean id= "ConnectionFactory" class= "ORg.springframework.jms.connection.CachingConnectionFactory "> <constructor-arg ref=" jmsfactory "/> &lt ;/bean> <bean id= "defaultdestination" class= "Org.apache.activemq.command.ActiveMQQueue" > <const Ructor-arg index= "0" value= "send2recv" ></constructor-arg> </bean> <bean id= "Jmstemplate" class= "Org.springframework.jms.core.JmsTemplate" > <property name= "connectionfactory" ref= "Jmsfactory" ></pro

    perty> <property name= "defaultdestination" ref= "defaultdestination" ></property> </bean> <bean id= "Jmslistenercontainerfactory" class= " Org.springframework.jms.config.DefaultJmsListenerContainerFactory "> <property name=" connectionfactory "ref= "ConnectionFactory"/> <!--the range of consumption that can be processed at the same time, write only one number representing the maximum value--<property name= "concurrency" value= "3-1 0 "/> </bean> </beans>

Send to queue

Package com.xxx.ws.service;
Import Com.xxx.ws.entity.Hi;
Import Org.apache.activemq.command.ActiveMQQueue;
Import Org.springframework.jms.core.JmsTemplate;
Import Org.springframework.jms.core.MessageCreator;

Import Org.springframework.stereotype.Service;
Import Javax.annotation.Resource;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import javax.jms.Session;

Import java.io.Serializable;
 /** * Created on 2017/1/24.

    */@Service public class Jmsmessagesender {@Resource private jmstemplate jmstemplate;
        /** * Send text to default destination * @param text */public void Send (final String text) { This.jmsTemplate.send (New Messagecreator () {@Override public Message createmessage (Ses
                Sion session) throws JMSException {Message message = Session.createtextmessage (text);
   Message.setjmsreplyto (New Activemqqueue ("Recv2send"));             return message;
    }
        }); }/** * Simplify the send by using Convertandsend * @param text */public void SendText (final stri
    ng text) {this.jmsTemplate.convertAndSend (text); }/** * Send text message to a specified destination * @param dest * @param text */public VO 
            ID Send (Final Destination dest,final String text) {this.jmsTemplate.send (dest, New Messagecreator () {
                @Override Public Message CreateMessage (session session) throws JMSException {
                Message message = Session.createtextmessage (text);
            return message;
    }
        }); public void Send (Final Object hi) {jmstemplate.send (new Messagecreator () {@Overri De public Message CreateMessage (session session) throws JMSException {return sess Ion.createobjectmessaGE ((Serializable) hi);
    }
        }); }


}

Consumption queue

package com.xxx.ws.service;
Import Org.apache.activemq.command.ActiveMQObjectMessage;
Import Org.apache.log4j.LogManager;
Import Org.apache.log4j.Logger;
Import Org.springframework.jms.annotation.JmsListener;
Import Org.springframework.jms.core.JmsTemplate;
Import Org.springframework.messaging.converter.MessageConverter;
Import Org.springframework.messaging.handler.annotation.SendTo;

Import Org.springframework.stereotype.Service;
Import Javax.annotation.Resource;
Import javax.jms.JMSException;
Import Javax.jms.Message;

Import Javax.jms.MessageListener;
 /** * Created on 2017/1/24.

    */@Service public class Jmsmessagereceiver {private final Logger Logger = Logmanager.getlogger (This.getclass ());



    @Resource private Jmstemplate jmstemplate; @JmsListener (Destination = "send2recv")//@SendTo ("recv2send") public void OnMessage (String text) throws Jmsexcept
    Ion {System.out.println ("Received:" + text); }
}

This will enable the production and consumption of messages in the spring project.

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.