I. Overview of the message queue
Message (Message) refers to the data transfer between applications. Message can be very simple, for example, only contains the text string, may be more complex, and may contain embedded objects.
Message Queue (Message Queue) is a communication between an application, the message can be returned immediately by the message system to ensure reliable delivery of the message. Post Owner shoved the messages posted to the MQ without tubes who will take the message users simply take a message from the MQ regardless of who posted. Such publishers and users do not know about each other.
Message Queue Middleware is a distributed system, an important component, mainly to solve the asynchronous messages, traffic clipping, coupling applications and other issues. High performance, high availability, scalable architecture and eventual consistency. Large-scale distributed systems is essential middleware. Currently using more message queue products ActiveMQ, RabbitMQ, ZeroMQ, Kafka, MetaMQ, RocketMQ and so on.
Life examples
Old-fashioned restaurant for fine dining postprandial need to stay in the seat, the middle can not leave the shop and go to something else, if you leave the shop and go to something else, a good meal, ordering people do not know.
The new restaurant for the meal, the restaurant will offer a "electronic trading" to the customer, the customer can not eat in the store, etc., you can go to nearby shopping, buy buy something, such as a good meal, the hands of "electronic trading" will sound, notify the customer can go back to eating.
Contrast the above two forms, the second case the same as the message queue, you can go deal with something else after the end point of meal, would not have to wait in the restaurant.
Second, the role of the message queue
It says the main message queue to solve the three problems of asynchronous processing, traffic clipping, coupling and other applications.
Asynchronous Processing
Scene Description: After the user registration system to send registered mail and SMS registration. There are two conventional manner, parallel and serial mode.
Serial mode: After successful registration information stored in the database, send text messages and email registration registration, after more than three steps are completed, the information will be successfully returned to the client.
Parallel Mode: After successful registration information stored in the database, while sending SMS and email registration registration , returned to the client after more than three tasks are completed, the difference with the serial mode is the parallel mode can increase processing time.
Traffic clipping
Application Coupling
Three, Active MQ
download
http://activemq.apache.org/components/classic/download/
installation
Direct decompression, then moved to the specified directory.
>tar zxvf apache-activemq-5.15.10-bin.tar.gz >mv ./apache-activemq-5.15.10 /usr/local
start up
>/usr/local/activemq-5.15.10/bin/activemq start # Check the startup state [root@cbooy bin]# jps 3168 Jps 2268 activemq.jar The default port number # activemq start of 61616 [root @ cbooy bin] # lsof -i: 61616 the COMMAND PID the USER FD the TYPE the DEVICE SIZE / OFF NODE NAME java 2268 root 132u IPv6 15719 0t0 TCP *:61616 (LISTEN)
Other basic commands
> ActiveMQ restart # restart > ActiveMQ STOP # Close > activemq start> /activemq_home/logs/activemq.log # landing information, print log
Starts the specified configuration file
./bin/activemq start xbean:/usr/local/activemq-5.15.10/conf/activemq.xml
The graphical interface supports background
- http://127.0.0.1:8161/admin
- The default username / password, admin / admin
- Graphical page description information
- Number Of Pending Messages
- Message Waiting consumption
- Queue is not the number of
- Number Of Consumers
- The number of consumers
- Messages Enqueued
- Message number into the team, comprising a total number of queued messages dequeued
- Messages Dequeued
- The team number of messages that the consumer spending news
- Number Of Pending Messages
Four, Java operating ActiveMQ
Dependent jar package
dependencies { compile('org.apache.activemq:activemq-all:5.15.9') compile('org.apache.activemq:activemq-pool:5.15.9') }
The first model: Queue
Production Process
- Create a connection factory object
- From the factory to establish a connection and open (Connection)
- Establishing a session (Session) from the connection
- Based session establishment Destination (Queue)
- Based session creation producer (Producer)
- Creating a message (Message) session on the basis of
- Producers will send out the message
- Resources Close
public class Producer { // address activemq services, default communication port 61616 Private static String the URL of Final = " tcp: //192.168.182.128: 61616 " ; // define the name of the queue Private Final static String queue_name = " Test-Queue " ; public static void main(String[] args) { MessageProducer producer = null; Session session = null; Connection connection = null; try { // create a connection factory object ActiveMQConnectionFactory connectionFactory = new new ActiveMQConnectionFactory (the URL of); // establish a connection and open (Connection) from the factory Connection = connectionFactory.createConnection (); connection.start(); // create a session (Session) connection from the session = connection.createSession ( to false , . 1 ); // based session establishment queue (Queue) Queue Queue = session.createQueue (queue_name); // based on the session to create producer (Producer) Producer = session.createProducer (Queue); for (int i = 0; i < 10; i++) { // Create a message session basis (the Message) TextMessage textMessage session.createTextMessage = ( " Test-MQ: " + I); // producer will send messages producer.send (textMessage); } } catch (Exception ex) { throw new IllegalStateException(ex); // Resource Close } finally { try { if (null != producer) { producer.close(); } } catch (JMSException e) { e.printStackTrace (); } try { if (null != session) { session.close(); } } catch (JMSException e) { e.printStackTrace (); } try { if (null != connection) { connection.close(); } } catch (JMSException e) { e.printStackTrace (); } } } }
After executing the above code, we can see the following situation in the management page:
Consumer Process
- Create a connection factory object
- From the factory to establish a connection and open (Connection)
- Establishing a session (Session) from the connection
- Based session establishment Destination (Queue)
- Based session creates consumer (Consumer)
- Consumers receive messages
- Resources Close
public class Consumer { // ActiveMQ service address, default communication port 61616 Private static Final String = the URL of "tcp: //192.168.182.128: 61616" ; // define the name of the queue Private static Final String queue_name = "Test-Queue" ; public static void main(String[] args) { MessageConsumer consumer = null; Session session = null; Connection connection = null; the try { // create a connection factory object ActiveMQConnectionFactory The connectionFactory = new new ActiveMQConnectionFactory (the URL); // establish a connection and open (Connection) from the factory Connection = connectionFactory.createConnection (); connection.start(); // create a session (Session) connection from the session = connection.createSession ( to false ,. 1 ); // based session establishment queue (Queue) Queue Queue = session.createQueue (queue_name); // based on the session to create consumer (Consumer) Consumer = session.createConsumer (Queue); // first embodiment of the received message, the received blocking // the Message Message consumer.receive = (); // System.out.println ( "Consumer to recive Message =" + Message); // second embodiment received message using a listener consumer.setMessageListener (MSG -> { TextMessage textMessage = (TextMessage) msg; try { System.out.println("textMessage = " + textMessage.getText()); } catch (JMSException e) { e.printStackTrace (); } }); } catch (Exception ex) { throw new IllegalStateException(ex); } } }
After executing the above code, we can see the following situation in the management page:
This time we run the two Consumer, due to the Consumer kinds of resources is not closed, it will remain and the connection of ActiveMQ.
And then run the Producer, we look at the phenomenon:
Information console print, the information Consumer1 consumption is an even number, the information Consumer2 consumption is odd, a message can only be a Consumer consumption.
The second mode: Topic
Production Process
- Create a connection factory object
- From the factory to establish a connection and open (Connection)
- Establishing a session (Session) from the connection
- Based session establishment destination (Topic)
- Based session creation producer (Producer)
- Creating a message (Message) session on the basis of
- Producers will send out the message
- Resources Close
public class Producer { // ActiveMQ service address, default communication port 61616 Private static Final String = the URL of "tcp: //192.168.182.128: 61616" ; // define the name of the queue Private static Final String TOPIC_NAME from = "Topic-Test" ; public static void main(String[] args) { MessageProducer producer = null; Session session = null; Connection connection = null; the try { // create a connection factory object ActiveMQConnectionFactory The connectionFactory = new new ActiveMQConnectionFactory (the URL); // establish a connection and open (Connection) from the factory Connection = connectionFactory.createConnection (); connection.start(); // create a session (Session) connection from the session = connection.createSession ( to false ,. 1 ); // based session establishment destination (Topic) Topic Topic = session.createTopic (TOPIC_NAME); // based on the session to create producer (Producer) Producer = session.createProducer (Topic); for (int i = 0; i < 10; i++) { // Create a message session basis (the Message) TextMessage textMessage session.createTextMessage = ( "Test-Topic:" + I); // producer will send messages producer.send (textMessage); } } catch (Exception ex) { throw new IllegalStateException(ex); // 资源关闭 } finally { try { if (null != producer) { producer.close(); } } catch (JMSException e) { e.printStackTrace (); } try { if (null != session) { session.close(); } } catch (JMSException e) { e.printStackTrace (); } try { if (null != connection) { connection.close(); } } catch (JMSException e) { e.printStackTrace (); } } } }
Consumer Process
- Create a connection factory object
- From the factory to establish a connection and open (Connection)
- Establishing a session (Session) from the connection
- Based session establishment destination (Topic)
- Based session creates consumer (Consumer)
- Consumers receive messages
- Resources Close
public class Consumer1 { // address activemq services, default communication port 61616 Private static Final String = the URL of "tcp: //192.168.182.128: 61616" ; // define the name of the queue Private static Final String TOPIC_NAME from = "Topic-Test" ; public static void main(String[] args) { MessageConsumer consumer = null; Session session = null; Connection connection = null; the try { // create a connection factory object ActiveMQConnectionFactory The connectionFactory = new new ActiveMQConnectionFactory (the URL); // establish a connection and open (Connection) from the factory Connection = connectionFactory.createConnection (); connection.start(); // create a session (Session) connection from the session = connection.createSession ( to false ,. 1 ); // based session establishment destination (Topic) Topic Topic = session.createTopic (TOPIC_NAME); // based on the session to create consumer (Consumer) Consumer = session.createConsumer (Topic); // first embodiment of the received message, the received blocking // the Message Message consumer.receive = (); // System.out.println ( "Consumer to recive Message =" + Message); // second embodiment received message using a listener consumer.setMessageListener (MSG -> { TextMessage textMessage = (TextMessage) msg; try { System.out.println("textMessage = " + textMessage.getText()); } catch (JMSException e) { e.printStackTrace (); } }); } catch (Exception ex) { throw new IllegalStateException(ex); } } }
Queue and Topic mode mode, the code is very similar, is to create a Queue, and the other is to create a Topic.
Now let's run three Consumer, and then run Producer, take a look at the phenomenon
Information printed in the console, all three Consumer consume all of the messages, a message can only be more Consumer consumption.
Five, SpringBoot integration