Getting Started with MQ (i)--MQ, JMS Understanding and ACTIVEMQ basic operations

Source: Internet
Author: User
Tags data structures message queue

First, MQ
1.1 About Message Queuing MQ
Message Queuing (MQ) is an application-to-application communication method. Applications communicate by writing and retrieving data (messages) for applications that enter and leave the queue, without requiring a private connection to link them. Message passing refers to the process of communicating between programs by sending data in a message, rather than by directly invoking each other, and directly invoking techniques such as remote procedure calls. Queuing refers to an application communicating through a queue. The use of queues removes the need for both receiving and sending applications to execute concurrently
1.2 MQ Features:
A typical representation of MQ's consumption-producer model, where one end writes messages continuously to the message queue, while the other end reads or subscribes to messages in the queue. MQ is similar to JMS, but the difference is that JMS is a standard and API definition for the Sun Java Messaging Middleware Service, and MQ follows the specific implementations and products of the AMQP protocol.

1.3 Usage Scenarios:
In the project, some operations without immediate return and time-consuming are extracted and processed asynchronously, which greatly saves the request response time of the server and improves the throughput of the system.

Second, JMS
Reference article: Https://baike.baidu.com/item/JMS/2836691?fr=aladdin
2.1 About JMS
JMS, the Java Message Service Application interface, is an API for message-oriented middleware (MOM) in the Java platform for sending messages between two applications, or distributed systems, for asynchronous communication. The Java Messaging Service is a platform-agnostic API, and the vast majority of MOM providers support JMS.

2.2. JMS Architecture

JMS is made up of the following elements
JMS Provider--an implementation of a JMS interface that connects to a message-oriented middleware. The provider can be a JMS implementation of the Java platform or a non-Java platform-oriented messaging middleware adapter (ACTIVEMQ,RABBITMQ, etc.).
JMS Client--the application or object (producer and consumer) that produces or consumes message-based Java
JMS Producer--a JMS client that creates and sends messages. (The activemq is reflected in generating the message object and storing the object in the message queue.) )
JMS consumer--the JMS client that receives the message. (Activemq to get the message object in the message queue for the appropriate business processing)
JMS messages-objects that pass data between JMS clients
JMS Queue--a region that holds messages that are sent for waiting to be read. Unlike the meaning implied by the name of the queue, the order in which messages are received is not necessarily the same as the order in which the messages are sent.
JMS topic-A mechanism that supports sending messages to multiple subscribers.

2.3 JMS Object Types
The Connection factory (ConnectionFactory) uses the connection factory to create a JMS connection.
A JMS connection (Connection) represents an active connection between the JMS client and the server side, which is established by the client by invoking the connection factory method.
A JMS session (session) indicates the state of the conversation between the JMS client and the JMS server. A JMS session is established on a JMS connection and represents a session thread between the client and the server.
JMS Purpose (Destination), also known as Message Queuing, is the actual source of the message.
The producer (message Producer) and consumer (message Consumer) objects are created by the session object for sending and receiving messages.

2.4 JMS messages are usually of two types:
① Point-to-point (point-to-point). In a point-to-point messaging system, messages are distributed to a single consumer. Point-to-point messages are often associated with queues (Javax.jms.Queue). " for this message, only one consumer will get the message "
② Publish/Subscribe (publish/subscribe). The Publish/Subscribe messaging system supports an event-driven model in which message producers and consumers are involved in message delivery. Producers publish events, and consumers subscribe to events of interest and use events. This type of message is typically associated with a specific topic (JAVAX.JMS.TOPIC). " for this message: Multiple consumers can get the message "

3. JMS and MQ relationships:
JMS is a technical specification for providing a messaging service that develops all the data structures and interaction processes throughout the messaging service delivery process. MQ, the Message Queuing service, is the ultimate implementation of message-oriented middleware (MOM), a true service provider, and the implementation of MQ can be based on JMS or other specifications or standards.

Two. ActiveMQ Understanding and operation
For MQ the ACTIVEMQ used this time.
1. Installation of ACTIVEMQ (Windows)

Download the installation package from the official website, http://activemq.apache.org/download.html
Directly decompression, into the corresponding bin directory, select the appropriate version, click Active.bat can
If you want to install it as a service, click Installservice.bat to install it as a service startup.
The picture is as follows:

When started, the ACTIVEMQ consumes two ports, one is the TCP port responsible for receiving the sending message: 61616, and one is the Web-based port that is responsible for user interface management: 8161. These two ports can be found in the XML below Conf.
After startup, the management interface Access address is: http://localhost:8161/admin/Default user name: admin Password: admin can be in the Conf folder under the Users.properties view
The picture is as follows:

2. Using Java Operation ACTIVEMQ

2.1 Producer: Generates the Message object and puts it into the queue. The specific code is as follows:

/** * Producer * @author Onionflower * */public class JMSProducer {private static final int sendnum = 10;
        public static void Main (string[] args) {//connection factory connectionfactory ConnectionFactory;
        Connection Connection Connection = null;
        session, the thread that accepts or sends a message sessions session;
        The destination of the message Destination Destination;
        Message producer MessageProducer MessageProducer;
        Example Factory connectionfactory = new Activemqconnectionfactory (Connectionconstants.brokenurl); try {//Get connection connection = Connectionfactory.createconnection (connectionconstants.username, connect
            Ionconstants.password);
            Start Connection Connection.start (); Create session//parameter 1:true: When the record is consumed, the data in the middle station is not deleted. False: When the record is consumed, the data in the middle station is deleted "Parameter 1 is true, the second argument is invalid"//parameter 2:session.auto_acknowledge is automatically confirmed, the client sends and receives the message does not need to do extra work. The exception also confirms the message, which should be confirmed by the client before execution//session.client_acknowledge. After the client receives the message, it mustThe acknowledge method of the javax.jms.Message must be called. The JMS server will not delete the message. You can not confirm the message in the failed//time, do not confirm the words will not be moved out of the queue, always exist, the next start to continue to accept. The connection to receive the message is kept open, and other consumers will not accept (normally no other consumer in the queue mode)//dups_ok_acknowledge allow a copy of the confirmation mode. Once a method call from the receiving application returns from the processing message, the Session object confirms the receipt of the message and allows duplicate acknowledgments.
            This mode is very effective when you need to consider the use of resources.
            Session = Connection.createsession (true, Session.auto_acknowledge);
            Create a message Queue Destination = Session.createqueue ("Firstdemo");
            Create message generation This messageproducer = session.createproducer (destination);

            Send Message SendMessage (session, MessageProducer);
        Session.commit ();
        } catch (JMSException e) {//TODO auto-generated catch block E.printstacktrace ();
        }} public static void SendMessage (Session session,messageproducer messageproducer) throws jmsexception{ for (int i=0;i<sendnum; i++) {TextMessage message = Session.createtextmessage ("ACTIVEMQ producer production messages, this is the" +i+ "secondary production
            ");
  Send a message          Messageproducer.send (message); }
    }
}

2.2 Consumer: Get the Message object from the queue the specific code is as follows:

/** * Message Consumer * @author onionflower * */public class Jmsconsumer {public static void main (string[] args) {

        ConnectionFactory ConnectionFactory;

        Connection Connection;

        Session session;
        Destination Destination;

        Message consumer Messageconsumer Messageconsumer;

        ConnectionFactory = new Activemqconnectionfactory (Connectionconstants.brokenurl); try {connection = Connectionfactory.createconnection (Connectionconstants.username, Connectionconstants.passwo

            RD);

            Connection.start ();

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

            Destination = Session.createqueue ("Firstdemo");

            Messageconsumer = Session.createconsumer (destination);
                while (true) {TextMessage TextMessage = (textmessage) messageconsumer.receive (10000); if (textmessage! = null) {SYSTEM.OUT.PRINTLN ("message received by ACTIVEMQ consumer:" +tExtmessage.gettext ());
                }else{break;
        }}} catch (JMSException e) {e.printstacktrace (); }

    }
}

Constant Helper Classes:

/**
 * Constants Use class
 * @author onionflower
 *
 *
/public class Connectionconstants {

    //Default user name
    public Static final String USERNAME = Activemqconnection.default_user;
    Default password public
    static final String PASSWORD = Activemqconnection.default_password;
    Default connection URL address public
    static final String brokenurl = Activemqconnection.default_broker_url;
}

The results of the operation are as follows:
1, start production and consumers, after the start, will be in the management interface can see the message object production and consumption situation, as follows:

The console is running as follows:

2, after running the program, we can return, the generator and the consumer program started, the program has been in the listening state.

The source code download address is as follows: http://download.csdn.net/download/u012151597/10174263

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.