Java ActiveMQ Tutorial (i) Understanding JMS and ActiveMQ Basic use (RPM)

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/luochengqiuse/p/4678020.html?utm_source=tuicool&utm_medium=referral

MQ has been used in recent projects and has been in the same divert as the yards. In recent days, I have studied the following, summarizing all the documents and understanding that I have seen.

I. Understanding JMS1. Overview

For JMS, Baidu Encyclopedia, this is introduced: JMS is the Java Messaging Service (Java Message Services) application interface is a Java platform for message-oriented middleware (MOM) API to send 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.

In short, JMS is a vendor-agnostic API used to access messaging system messages. It is similar to JDBC (Java Database Connectivity), providing the ability to communicate asynchronously between applications.

JMS1.0 is a specification specified in JSR 194 (click on the JSR specification). Currently the latest specification is the JSR 343,jms2.0.

Well, to say so much, actually just to say that JMS is just a set of API interfaces defined by Sun in order to unify the vendor's interface specification.

2. JMS Architecture

The description is as follows:

    • JMS providers (implementations of JMS, such as Activemq jbossmq, etc.)
    • JMS Client (a program or object that uses a provider to send a message, for example, in 12306, is responsible for sending a ticket to the processing queue, which is used to resolve the issue of ticketing peaks, then the program that sends the message to the queue and the program that gets the message from the queue is called the customer)
    • JMS producer, JMS consumer (producer and customer responsible for creating and sending messages, consumer is the customer responsible for receiving and processing the message)
    • JMS messages (objects that pass data between JMS clients)
    • JMS Queue (a region that holds messages that are sent for waiting to be read)
    • JMS topic (A mechanism that supports sending messages to multiple subscribers)
3. JMS Object Model
    • The Connection factory (connectionfactory) client uses Jndi to find the connection factory and then creates a JMS connection using the connection factory.
    • A JMS 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.
    • The JMS sessions session identifies the session state of the JMS client and server side. A session is established on a JMS connection to identify a session process between the client and the server.
    • JMS Purpose Destinatio, also known as Message Queuing, is the actual message source
    • Producers and consumers
    • Message type, divided into queue type (first FIFO) and subscription type
Two. ActiveMQ1. Installation of ACTIVEMQ
    1. Download the installation package from the official website, http://activemq.apache.org/download.html
    2. Give permission to run chmod +x,windows can ignore this step
    3. Run./active Start | Stop

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. The HTTP server uses Jettry.
One problem here is that after MQ is started, a long time management interface can be displayed.

2. Accessing Activemq in Java

Include the bean Code first:

PublicClassMqbeanImplementsserializable{Private Integer age;private String name; public Integer getAge () {return age;} public void setage (Integer age) {this.age = Age;} public String getName () {return name;} public void setname (String name) {this.name = Name }} 
2.1 Sending of queue messages:
PublicStaticvoidMainString[] args) {connectionfactory connectionfactory; Connection Connection; Session session; Destination Destination; MessageProducer producer; ConnectionFactory =New Activemqconnectionfactory ("Admin","Admin","tcp://192.168.3.159:61616");try {connection = connectionfactory.createconnection (); Connection.start ();The first parameter is whether it is a transactional message, set to True, and the second argument is invalidThe second parameter isSession.auto_acknowledge for automatic acknowledgement, the client sends and receives messages without doing extra work. The exception will also confirm the message, which should be confirmed before executionThe Session.client_acknowledge is confirmed for the client. After the client receives the message, the Javax.jms.Message's acknowledge method must be called. The JMS server will not delete the message. Can be in the failedThe time does not confirm the message, does not confirm the word will not move out the queue, always exists, next start continues to accept. The connection to receive messages continues to open, and other consumers will not accept (normally there is no other consumer in queue mode)Dups_ok_acknowledge allows the confirmation mode of the replica. 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.//to be tested session = Connection.createsession (false, Session.client_acknowledge); Destination = Session.createqueue (//priority cannot affect FIFO ... What is the use of that? Mqbean Bean = new Mqbean (); Bean.setage (13); Span class= "Hljs-keyword" >for (int i=0;i<100;i++" {bean.setname ( "Xiao Huang" +i); Producer.send (session.createobjectmessage (bean)); } producer.close (); System. out.println ( "hehe");} catch (jmsexception e) {e.printstacktrace ();}}       

Note: In the above code, the confirmation mode has three kinds, inside the Dups_ok_acknowledge and Auto_acknowledge has not understood what difference. Because it cannot be tested. But I probably understand some of it. In fact, the process of processing the message is essentially the MQ decision:

    1. Messages are routed from the build party client to the messaging server.
    2. The message server reads the message.
    3. Messages are placed in the persistent memory (for reliability reasons).
    4. The message server acknowledges receipt of the message (for reliability reasons).
    5. The message server determines the route of the message.
    6. The message server writes out a message.
    7. Messages are routed from the messaging server to the consumer client.
    8. The consumer client acknowledges receipt of the message (for reliability reasons).
    9. The Messaging server handles client acknowledgements (for reliability reasons).
    10. The message server determines that the client acknowledgment has been processed.

These steps are sequential, so any step can become a bottleneck for the delivery of messages from the generator client to the consumer client. Most of these steps depend on the physical characteristics of the messaging system: network bandwidth, computer processing speed, messaging server architecture, and so on. However, there are a few steps that also depend on the characteristics of the messaging application and the level of reliability that the application requires.
In fact, it is based on the choice of reliability or performance.

2.2 Receiving of queue messages:
PublicStaticvoidMainString[] args) {connectionfactory connectionfactory;CONNECTION:JMS client-to-JMS Provider connection Connection Connection =NullSession: A thread that sends or receives a message session session;Destination: The destination of the message, to whom the message is sent. Destination Destination;Consumer, message recipient Messageconsumer consumer; ConnectionFactory =New Activemqconnectionfactory ("Admin","Admin","tcp://192.168.3.159:61616");try {Construction gets the connection object from the factory connection = Connectionfactory.createconnection ();Start Connection.start ();Get Operation ConnectionThis best still has a business session = Connection.createsession (Boolean.false, Session.auto_acknowledge);Get session Note parameter value Xingbo.xu-queue is a server queue that must be configured in ACTIVEMQ console destination = Session.createqueue ("Test-queue"); Consumer = session.createconsumer (destination); Consumer.setmessagelistener (new MessageListener () {@override public void onMessage (message message) {try {mqbean bean = (Mqbean) ((objectmessage) message). GetObject (); System. out.println (bean); if (null! = message) {System. Out.println ( "Receive Message" + Bean.getname ());}} catch (Exception e) {//TODO: Handle exception}}); } catch (Exception e) {e.printstacktrace ();}}       

Note: For queues, a simpler optimization strategy should be to queue the load. Since each consumer is single-threaded, multiple consumers can be set up to speed up the drive.
You can copy a consumer's own test and add the sleep test effect to the consumer.

2.3 Sending a subscription message
PublicStaticvoidMainString[] args) {connectionfactory connectionfactory; Connection Connection; Session session; Destination Destination; MessageProducer producer; ConnectionFactory =New Activemqconnectionfactory ("Admin","Admin","tcp://192.168.3.159:61616");try {connection = connectionfactory.createconnection (); Connection.start (); session = Connection.createsession (false, Session.client_acknowledge); Destination = Session.createtopic ("Test-topic"); producer = Session.createproducer (destination); Producer.setdeliverymode (deliverymode.non_persistent); //priority cannot affect FIFO ... What is the use of that? Mqbean Bean = new Mqbean (); Bean.setage (13); For (int i=0;i<100;i++) {thread.sleep (+); Bean.setname ("small yellow" +i); Producer.send ( Session.createobjectmessage (bean)); } producer.close (); System. out.println ("hehe");} catch (Exception e) {e.printstacktrace ();}}             
2.4 Receiving a subscription message
PublicStaticvoidMainString[] args) {connectionfactory connectionfactory;CONNECTION:JMS client-to-JMS Provider connection Connection Connection =NullSession: A thread that sends or receives a message session session;Destination: The destination of the message, to whom the message is sent. Destination Destination;Consumer, message recipient Messageconsumer consumer; ConnectionFactory =New Activemqconnectionfactory ("Admin","Admin","tcp://192.168.3.159:61616");try {Construction gets the connection object from the factory connection = Connectionfactory.createconnection ();Start Connection.start ();Get Operation ConnectionThis best still has a business session = Connection.createsession (Boolean.false, Session.auto_acknowledge);Get session Note parameter value Xingbo.xu-queue is a server queue that must be configured in ACTIVEMQ console destination = Session.createqueue ("Test-queue"); Consumer = session.createconsumer (destination); Consumer.setmessagelistener (new MessageListener () {@Override public void onMessage (message message) { try {mqbean bean = (Mqbean) ((objectmessage) message). GetObject (); System. out.println (Bean); if (null! = message) {System.  Out.println ("received message" + Bean.getname ());}} catch (Exception e) { // Todo:handle Exception}}}); } catch (Exception e) {e.printstacktrace ();}}            

After the message is sent, if not received, you can log in to your own MQ Administration page: http://192.168.3.159:8161/admin/, the default account password is admin, view messages in the queue

Number of Pending Messages messages waiting to be consumed this is the quantity of the current outstanding queue. Can be understood as total number of received-Total out of queue
Messages enqueued The total number of messages entered into the queue, including the queue. This number only increases.
Messages dequeued out a queue of messages can be understood as consumption of this consumption of the quantity

Java ActiveMQ Tutorial (i) Understanding JMS and ActiveMQ Basic use (RPM)

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.