Java ActiveMQ understand JMS and ActiveMQ basic use __java

Source: Internet
Author: User
Tags generator ticket

The most recent project used MQ, which had been divert like a farmer. In the last few days, I've looked at all the documents and the information I've seen. I. Understanding JMS 1. Overview

For JMS, the Baidu Encyclopedia is introduced: the JMS, Java Messaging Service (Java Message Services) application interface is a Java platform for message-oriented middleware (MOM) APIs for sending messages between two applications, or distributed systems. For asynchronous communication. The Java Messaging Service is a platform-independent API, with most MOM providers supporting JMS.

In short, JMS is a vendor-independent API for accessing message-and-send system messages. It is similar to JDBC (Java Database connectivity), providing the ability to communicate asynchronously between applications.

JMS1.0 is the specification stipulated in JSR 194 (for the JSR specification, click). Currently the latest specification is the JSR 343,jms2.0.

Okay, so much, it's just saying that JMS is just a set of API interfaces that Sun has defined to unify the vendor's interface specification. 2. JMS Architecture

Described below: JMS providers (implementations of JMS, such as Activemq jbossmq, etc.) JMS clients (Programs or objects that use the provider to send messages, for example, in 12306, responsible for sending a ticket message to the processing queue to solve the ticket-purchase peak problem, Programs that send messages to queues and programs that get messages from queues are called customers. JMS producers, JMS consumers (producers and customers responsible for creating and sending messages, consumers are customers responsible for receiving and processing messages) JMS messages (objects that pass data between JMS clients) JMS queues (a zone that holds messages that are sent for waiting to be read) a JMS topic (a mechanism that supports sending messages to multiple subscribers) 3. The JMS object Model Connection factory (connectionfactory) client uses Jndi lookup to connect the 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 method that connects the factory. JMS session Sessions Identify the session state of the JMS client and server side. The session is built on a JMS connection, identifying a session process between the client and the server. JMS Purpose Destinatio, also known as Message Queuing, is the actual message source producer and consumer message type, divided into queue type (priority first out) and subscription type two ActiveMQ 1. ACTIVEMQ installation from the official website download installation package, http://activemq.apache.org/download.html give run permissions chmod +x,windows can ignore this step run./active Start | Stop

Once started, Activemq consumes two ports, one is the TCP port responsible for receiving sending messages: 61616, and one is based on the web responsible for user interface management port: 8161. These two ports can be found in the XML below Conf. The HTTP server uses Jettry. The problem here is that after you start MQ, a long time management interface can be displayed. 2. Use Java to access ACTIVEMQ

Attach the Bean code first:

public class Mqbean implements serializable{
	private Integer;
	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 Queue Message delivery:
public static void Main (string[] 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 argument is a transactional message, set to True, the second argument is invalid//The second parameter is//session.auto_acknowledge for automatic confirmation, and the client sends and receives messages without additional effort. The exception also confirms the message, which should be confirmed before execution//session.client_acknowledge for the client. After the client receives the message, it must call the Javax.jms.Message acknowledge method. The JMS server will not delete the message. Can be in the failure//time not confirm the message, do not confirm the words will not be moved out of the queue, always exist, the next start continue to accept. The connection that receives the message continues to open, and other consumers do not accept (normally there is no other consumer in the queue mode)//dups_ok_acknowledge allows the acknowledgement mode of the replica. Once the recipient application's method call returns from the processing message, the Session object confirms the receipt of the message, and allows duplicate acknowledgments.
		This pattern works well when you need to consider resource usage.
		To test session = Connection.createsession (false, Session.client_acknowledge);
		Destination = Session.createqueue ("Test-queue");
		Producer = Session.createproducer (destination);
		Producer.setdeliverymode (deliverymode.non_persistent);Priority does not affect advanced first out ...
		What is this usefulness? Mqbean bean = new Mqbean ();
		Bean.setage (13);
			for (int i=0;i<100;i++) {bean.setname ("small yellow" +i);
		Producer.send (Session.createobjectmessage (bean));
		} producer.close ();
	System.out.println ("hehe");
	catch (JMSException e) {e.printstacktrace (); }
}

Note: In the above code, there are three types of validation patterns, Dups_ok_acknowledge and Auto_acknowledge have not understood the difference. Because it cannot be tested. But probably also understood a few. It is primarily the process of MQ processing messages that determines that messages are routed from the generator client to the message server. The message server reads the message. Messages are placed in persistent storage (for reliability reasons). The message server confirms receipt of the message (for reliability reasons). The message server determines the route of the message. The message server writes out a message. Messages are delivered from the message server to the consumer client. The consumer client confirms receipt of the message (for reliability reasons). The message server handles client acknowledgments (for reliability reasons). The message server determines that client confirmation has been processed.

These steps are sequential, so any step can be a bottleneck in the routing 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, and messaging server architecture, among other things. However, there are steps that depend on the characteristics of the messaging application and the level of reliability that the application requires. In fact, it is based on reliability or performance choice. 2.2 Receipt of queue messages:

public static void Main (string[] args) {connectionfactory connectionfactory;
	CONNECTION:JMS Client to JMS Provider connection Connection Connection = null;
	Session: A thread that sends or receives messages;  
	Destination: The destination of the message, and to whom the message is sent.
	Destination destination;
	Consumer, message receiver Messageconsumer consumer;
	ConnectionFactory = new Activemqconnectionfactory ("admin", "admin", "tcp://192.168.3.159:61616");
		try {//construct Gets the connection object from the factory connection = Connectionfactory.createconnection ();
		Start Connection.start ();
		Get operation connection//This is the best or have a transaction 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 messages" + bean.getname ());
	The catch (Exception e) {//Todo:handle Exception}}});
	catch (Exception e) {e.printstacktrace (); }
}

Note: For queues, a simpler optimization strategy should be a queue-load. Because each consumer is single-threaded, you can set up multiple consumers to improve speed. You can copy a consumer's own test to add a sleep test effect to the consumer. send a 2.3 subscription message

public static void Main (string[] 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 does not affect advanced first out ...
		What is this usefulness? Mqbean bean = new Mqbean ();
		Bean.setage (13);
			for (int i=0;i<100;i++) {thread.sleep (1000);
			Bean.setname ("Xiao Huang" +i);
		Producer.send (Session.createobjectmessage (bean));
		} producer.close ();
	System.out.println ("hehe");
	catch (Exception e) {e.printstacktrace (); }
}
2.4 Receiving of subscription messages
public static void Main (string[] args) {connectionfactory connectionfactory;
	CONNECTION:JMS Client to JMS Provider connection Connection Connection = null;
	Session: A thread that sends or receives messages;  
	Destination: The destination of the message, and to whom the message is sent.
	Destination destination;
	Consumer, message receiver Messageconsumer consumer;
	ConnectionFactory = new Activemqconnectionfactory ("admin", "admin", "tcp://192.168.3.159:61616");
		try {//construct Gets the connection object from the factory connection = Connectionfactory.createconnection ();
		Start Connection.start ();
		Get operation connection//This is the best or have a transaction 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 messages" + bean.getname ());
	The catch (Exception e) {//Todo:handle Exception}}});
	catch (Exception e) {e.printstacktrace (); }
}

After the message is sent, if not received, you can login to their MQ Admin page: http://192.168.3.159:8161/admin/, the default account password is admin, view the message in the queue

Number of Pending Messages the message waiting to be consumed this is the amount of the currently outstanding queue. Can be understood as total receive number-Total out queue number

Messages enqueued The total number of messages entering the queue, including the queue. This number is only increasing.

The message that Messages dequeued out of the queue can be understood as the amount of consumption that is consumed.

This article is reproduced from: http://www.cnblogs.com/luochengqiuse/p/4678020.html

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.