Message middleware--ActiveMQ&JMS message service

### Messaging middleware ###

 
----------
 

**Message middleware**

 
1. Overview of message middleware
2. Application scenarios of message middleware (see the outline document to understand the application scenarios of message queues)
* Asynchronous processing
* Application decoupling
* Traffic clipping
* Information communication
 
----------
 

### JMS Messaging Service ###

 
----------
 

**Overview of JMS**

 
1. Overview of JMS Message Service
2. JMS message model
* P2P mode
* Pub/Sub mode
 
3. The way of message consumption
* Synchronization method---manual
* Asynchronous way---listener monitoring
 
4. JMS programming model
 
----------

 

### Messaging middleware: ActiveMQ ###

 
----------
 

**ActiveMQ download and installation**

 
1. Download and install ActiveMQ
* Find the compressed file of ActiveMQ in the data, decompress the apache-activemq-5.14.5-bin.zip file
* Double-click to run: activemq.bat file to start the service
 
2. Test whether ActiveMQ is installed successfully
* Open a browser and enter: http://localhost:8161
 
3. Click the Manage ActiveMQ broker connection to view the published messages in ActiveMQ, etc.
* Username and password are both: admin
 
----------
 

**Introduction to ActiveMQ's message queue method** (P2P mode)

 
1. Introduce the coordinate dependency of ActiveMQ and Spring to integrate JMS in the pom.xml file of the parent project (already introduced in the project)
<!-- activemq start -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.2.0</version>
</dependency>
 
<!-- activemq end -->
 
<!-- spring and mq integration start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.7</version>
</dependency>
<!-- spring and mq integration end -->
 
2. ActiveMQ's starter program for sending messages to message queues (without using Spring to integrate JMS)
@Test
public void sendQueueMessage() throws JMSException {
// 1 Create a connection factory
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
 
// 2 use the factory, create the connection
Connection connection = factory.createConnection();
 
// 3 start the connection
connection.start();
 
// 4 Use the connection to create a session, true means start a transaction, and a transaction needs to be provided after the code is executed
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
 
// 5 Create a queue formation (myQueue--the name of the queue)/topic-------------session creation
Queue queue = session.createQueue("myQueue");
// 6 Create producer ------------- session creation
MessageProducer producer = session.createProducer(queue);
// 7 Create message----text message-----session creation
TextMessage message = session.createTextMessage();
message.setText("helloworld!!!");
 
// 8 send message
producer.send(message);
 
// 9 commit the transaction
session.commit();
session.close();
connection.close();
}
 
3. ActiveMQ gets the message from the message queue
@Test
public void receiverQueueMessage() throws JMSException {
// 1 Create a connection factory
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
// 2 use the factory, create the connection
Connection connection = factory.createConnection();
// 3 start the connection
connection.start();
// 4 Use the connection to create a session, true means start a transaction, and a transaction needs to be provided after the code is executed
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
// 5 Create queue formation (hello--the name of the queue)/topic------------session creation
Queue queue = session.createQueue("myQueue");
// 6 Create consumer ------------- session creation
MessageConsumer consumer = session.createConsumer(queue);
 
// 7 Receive message----text format
TextMessage receive = (TextMessage) consumer.receive();
String text = receive.getText();
System.out.println("Received message====" + text);
 
// 8 commit the transaction
session.commit();
session.close();
connection.close();
 
}
 
4. Use the listener to consume messages from the queue
/**
*Asynchronous way
Queue is accepted by the Listener method, which is used for many times.
If there are multiple listener listeners, execute alternately
* @throws Exception
*/
@Test
public void receiverQueueListener() throws Exception{
// 1 Create a connection factory
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
// 2 use the factory, create the connection
Connection connection = factory.createConnection();
// 3 start the connection
connection.start();
// 4 Use a connection to create a session, true means start a transaction, and a transaction needs to be provided after the code is executed. // Things that cannot be used in an infinite loop
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 5 Create queue formation (hello--the name of the queue)/topic------------session creation
Queue queue = session.createQueue("myQueue");
// 6 Create consumer ------------- session creation
MessageConsumer consumer = session.createConsumer(queue);
 
//7 // Add a listener to the consumer
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message msg) {
TextMessage message = (TextMessage) msg;
try {
System.out.println("The message received by Listener1111111111 is =="+message.getText());
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
});
 
while(true){}
// The way to use the listener cannot be closed, the listener needs to work all the time
// session.commit();
// session.close();
// connection.close();
}
 
 

**Getting started with ActiveMQ's message subscription method** (Pub/Sub mode)

/**
* Topic send
* @throws JMSException
*/
@Test
public void sendTopicMessage() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
 
// create a message subscription
Topic topic = session.createTopic("myTopic");
// create producer
MessageProducer producer = session.createProducer(topic);
// Create a message, a set of messages that can store key value
MapMessage message = session.createMapMessage();
message.setString("username", "cgx");
message.setString("password", "123456");
// send messages
producer.send(message);
// commit the transaction
session.commit();
session.close();
connection.close();
}
 
/**
* Topic accepts
*
* @throws JMSException
*/
@Test
public void testReceiverMessage() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
 
// create a message subscription
Topic topic = session.createTopic("myTopic");
// create consumer
MessageConsumer consumer = session.createConsumer(topic);
// receive message
MapMessage message = (MapMessage) consumer.receive();
System.out.println(message.getString("username"));
System.out.println(message.getString("password"));
 
session.commit();
session.close();
connection.close();
}
 
/**
* Topic accepts Listener listening method
*
* @throws Exception
*/
@Test
public void receiverQueueListener() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// create a message subscription
Topic topic = session.createTopic("myTopic");
// create consumer
MessageConsumer consumer = session.createConsumer(topic);
 
// Add a listener to the consumer and add a listener to the consumer
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message msg) {
MapMessage message = (MapMessage) msg;
try {
System.out.println(message.getString("username"));
System.out.println(message.getString("password"));
} catch (JMSException e) {
e.printStackTrace ();
}
}
});
 
while (true) {
 
}
 
}
 
 
 

### Spring Integration with ActiveMQ ###★★★★★

 
----------
 
**Spring integrates ActiveMQ**★★★★★
 
1. Create a configuration file of applicationContext-mq.xml and import constraints ★★★★★
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
xmlns:amq="http://activemq.apache.org/schema/core"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd">
 
</beans>
2. The specific configuration is as follows★★★★★
applicationContext-mq.xml====================Message sending of mq (message producer)
<!-- configure connection factory -->
<!-- ActiveMQ connection factory -->
<!-- The ConnectionFactory that can really generate Connection is provided by the corresponding JMS service vendor -->
<!-- If connected to the network: tcp://ip:61616; not connected to the network: tcp://localhost:61616 and username, password -->
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://localhost:61616" userName="admin" password="admin" />
 
<!-- Spring Caching connection factory -->
<!-- The ConnectionFactory that Spring uses to manage the real ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<!-- The target ConnectionFactory corresponds to the real ConnectionFactory that can generate JMS Connection -->
<property name="targetConnectionFactory" ref="amqConnectionFactory"></property>
<!-- The number of Session caches is related to the number of links -->
<property name="sessionCacheSize" value="100" />
</bean>
 
<!-- Define the Queue type of JmsTemplate-->★★★★★
<bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- This connectionFactory corresponds to the ConnectionFactory object provided by Spring we defined -->
<constructor-arg ref="connectionFactory" />
<!-- Non-pub/sub model (pub/sub), ie queue mode-->
<property name="pubSubDomain" value="false" />
</bean>
 
<!-- Define the Topic type of JmsTemplate-->★★★★★
<bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate" >
<!-- This connectionFactory corresponds to the ConnectionFactory object provided by Spring we defined -->
<constructor-arg ref="connectionFactory" />
<!-- pub/sub model (pub/sub) -->
<property name="pubSubDomain" value="true" />
</bean>
 
3. The code to send the message is as follows★★★★★
1. Queue method: ★★★★★
@Autowired
@Qualifier(value="jmsQueueTemplate")
private JmsTemplate queueTemplate;//Queue
 
 
/**
* Queue sends messages---spring framework
*/
@Test
public void sendQueueMessage() {
// Send message construction parameters to specify the target, because the queue and subscription mode in the configuration file are distinguished from false and true by id
queueTemplate.send("myQueue", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
// Use the session to create a message and send it
TextMessage textMessage = session.createTextMessage("Test sending queue messages with spring framework");
return textMessage;
}
});
}
2.Topic method: ★★★★★
@Autowired
@Qualifier(value = "jmsTopicTemplate")
private JmsTemplate topicTemplate;//Topic
 
/**
* Topic send message---spring framework
*/
@Test
public void sendTopicMessage() {
topicTemplate.send("spring_topic", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("username", "mdzz");
return mapMessage;
}
});
}
 
4. The code for receiving the message is as follows ========== Manual is not recommended, use the listener to get it asynchronously
/**
* Queue receives messages---spring framework
* Manual synchronization: not recommended
* receive("myQueue") wants to write the destination, if the destination is not written, it will report the error NO defaultDestination that the destination cannot be found
*/
@Test
public void receiverMessage() {
//Receive message textMessage type
TextMessage textMessage = (TextMessage) queueTemplate.receive("myQueue");
 
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace ();
}
}
 
 
**Spring Configuration Listener**★★★★★★★★★★★★★★★
 
1. Writing custom listener code---receiving messages---spring framework---implementing the MessageListener interface★★★★★
1.Queue:★★★★★
@Component(value="queueConsumer1")
public class QueueListener implements MessageListener {
 
@Override
public void onMessage(Message arg0) {
// forcibly convert arg0
TextMessage textMessage = (TextMessage) arg0;
try {
// output message
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace ();
}
}
 
}
 
2.Topic: send one, both will be accepted
@Component
public class TopicConsumer1 implements MessageListener {
 
@Override
public void onMessage(Message arg0) {
MapMessage mapMessage = (MapMessage) arg0;
try {
System.out.println("TopicConsumer1===="+mapMessage.getString("username"));
} catch (JMSException e) {
e.printStackTrace ();
}
}
 
}
 
@Component
public class TopicConsumer2 implements MessageListener {
 
2. Write the configuration file
applicationContext-mq-consumer.xml =============Message acceptance of mq (responsible for listening to accept messages)
<!-- scan package -->
<context:component-scan base-package="com.itcast.jms.consumer" />
 
<!-- ActiveMQ connection factory -->
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="tcp://localhost:61616" userName="admin" password="admin" />
 
<!-- Spring Caching connection factory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="amqConnectionFactory"></property>
<property name="sessionCacheSize" value="100" />
</bean>
 
<!-- Message producer start--> of Spring JmsTemplate
<jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory">
<jms:listener destination="myQueue" ref="queueConsumer1"/>---------custom listener★★★★★
</jms:listener-container>
 
<jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory">
<jms:listener destination="spring_topic" ref="topicConsumer1"/>---------custom listener★★★★★
<jms:listener destination="spring_topic" ref="topicConsumer2" />---------custom listener★★★★★
</jms:listener-container>
 
 
3. Without starting the project, start the spring configuration file applicationContext-mq-consumer.xml, you can use the following method
Create a new test class and let it start all the time, so that the spring configuration file is always loaded
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-mq-consumer.xml")
public class SpringQueueListenerTest {
 
@Test
public void test(){
while(true);
}
}
4. As soon as the sender (send message---spring framework) starts, the listener will listen to it, and it will output: The test sends a queue message in combination with the spring framework ★★★★★
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324759905&siteId=291194637