ActiveMQ message queue from entry into practice (4) - Spring JMS messaging using

JavaMessage Service ( Java Message Service , ) JMSis a Javastandard that defines a common API uses the news agency. In the JMSprior appearance, each has a private news agency API, which makes the message code between different proxy difficult to GM. But with JMSall achieve compliance with specifications use a common interface, which is similar to JDBCprovide a common interface to the same database operations.

SpringTemplate-based abstraction to JMSprovide support, this template is JmsTemplate. Use JmsTemplate , can be very easy to send messages in the message queues and topics the production side, the party that consume messages can also be very easily receive these messages.

QueueAnd Topiccomparison is shown below:

image.png

 

Use maven dependencies management, increase pom.xml file as follows:

<dependencies>
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-all</artifactId>
		<version>5.11.0</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jms</artifactId>
		<version>4.1.4.RELEASE</version>
	</dependency>
	<dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-test</artifactId>  
        <version>4.1.4.RELEASE</version>  
    </dependency> 
</dependencies>

  

Transceiver queue (Queue) message

Point to Point message, if there is no consumer in the listen queue, the message will remain in the queue until the message until the consumer is connected to the queue. Such messaging model or model lazy polling model in the traditional sense. In this model, the message is not a message is automatically pushed to the consumer, but to obtain the request (pull mode) from the message queue by the consumer.

 

Spring configuration file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- 配置JMS连接工厂 -->
	<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<property name="brokerURL" value="failover:(tcp://localhost:61616)" />
	</bean>
	
	<!-- 定义消息队列(Queue) -->
	<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
	</ the bean>
		</ Arg-constructor>
		<constructor-Arg>
		<! - set message queue name ->
			<value> Queue1 </ value>
	 
	<-! JMS template configuration (Queue), JMS Spring provide tools, it sends, receives messages. -> 
	<the bean ID = "JmsTemplate" class = "org.springframework.jms.core.JmsTemplate"> 
		<Property name = "The connectionFactory" REF = "The connectionFactory" /> 
		<Property name = "defaultDestination" REF = "queueDestination" /> 
		<Property name = "the receiveTimeout" value = "10000" /> 
	</ the bean> 
	
	<-! message Queue Manufacturer -> 
	<the bean ID = "producerService" class = "com.yoodb.mq.queue.ProducerServiceImpl "> 
		<Property name =" the JmsTemplate "ref =" the JmsTemplate "> </ Property> 
	</ bean> 

	<-! message Queue consumer ->

 

Using the message producer Spring JMSmessage, reducing code duplication (interface class ProducerServicecode is omitted) is as follows:

package com.yoodb.mq.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class ProducerServiceImpl implements ProducerService {

  private JmsTemplate jmsTemplate;
  
  /**
   * 向指定队列发送消息
   */
  public void sendMessage(Destination destination, final String msg) {
    System.out.println("向队列" + destination.toString() + "发送了消息___" + msg);
    jmsTemplate.send(destination, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(msg);
      }
    });
  }

/**
 * 向默认队列发送消息
 */
  public void sendMessage(final String msg) {
	String destination =  jmsTemplate.getDefaultDestination().toString();
    System.out.println("向队列" +destination+ "发送了消息___" + msg);
    jmsTemplate.send(new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(msg);
      }
    });

  }

  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }

}

 

A message consumer code is as follows:

package com.yoodb.mq.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class ConsumerServiceImpl implements ConsumerService {

	private JmsTemplate jmsTemplate;

	/**
	 * 接受消息
	 */
	public void receive(Destination destination) {
		TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
		try {
			System.out.println("从队列" + destination.toString() + "收到了消息:\t"
					+ tm.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

}

 

Message queue listener, when receiving the message, the message can not consumer code way, Spring JMS messaging also provides a listening mode, the corresponding configuration content and code.

Spring configuration file as follows:

<! - defined message queue (Queue), we listen for a new queue, queue2 -> 
<bean the above mentioned id = "queueDestination2" class = "org.apache.activemq.command.ActiveMQQueue"> 
	<! - Set the Message Queue name -> 
	<constructor-Arg> 
		<value> Queue2 </ value> 
	</ Arg-constructor> 
</ the bean> 

<-! listener configuration message queue (queue), the code is given below, only one method onMessage -> 
<the bean ID = "queueMessageListener" class = "com.yoodb.mq.queue.QueueMessageListener" /> 

<-! message listener container (queue), connected to the plant configuration, the queue is Queue2 listening, the listener is above listener defined -> 
<the bean ID = "jmsContainer" 
	class = "org.springframework.jms.listener.DefaultMessageListenerContainer"> 
	<Property name = "the connectionFactory" REF = "the connectionFactory"/>
	<property name="destination" ref="queueDestination2" />
	<property name="messageListener" ref="queueMessageListener" />
</bean>

 

Listener class code as follows:

com.yoodb.mq.queue Package; 

Import javax.jms.JMSException,; 
Import the javax.jms.Message; 
Import the javax.jms.MessageListener; 
Import the javax.jms.TextMessage; 

public class QueueMessageListener the implements the MessageListener { 
        // the message is received when automatic call the method. 
	void the onMessage public (the Message Message) { 
		TextMessage (TM) = (TextMessage) Message; 
		the try { 
			System.out.println ( "ConsumerMessageListener received text message: \ T" 
					+ tm.getText ()); 
		} the catch (a JMSException E) { 
			E .printStackTrace (); 
		} 
	} 

}

 

Theme (Topic) messaging

pub / sub messaging model is basically a push model. In this model, the message will automatically broadcast, news consumers need to get a new message through polling or actively requests theme. When using Spring JMS, themes [publish / subscribe] (Topic) and major differences in the model for the message queue JmsTemplate, "pubSubDomain" is set to True. If True, it is Topic; if it is false or default, is the Queue.

<property name="pubSubDomain" value="true" />

 

Spring configuration file as follows:

<!-- 定义消息主题(Topic) -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg>
    <value>guo_topic</value>
    </constructor-arg>
</bean>

<!-- 配置JMS模板(Topic),pubSubDomain="true"-->
<bean id="topicJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestination" ref="topicDestination" />
    <property name="pubSubDomain" value="true" />
    <property name="receiveTimeout" value="10000" />
</bean>

<!--topic消息发布者 -->
<bean id="topicProvider" class="com.yoodb.mq.topic.TopicProvider">
    <Property name = "topicJmsTemplate" ref = "topicJmsTemplate"> </ Property> 
</ bean> 

<-! message subject and theme listener can configure multiple monitor vessel that more subscribers -> 
<! - news theme listener (topic) -> 
<bean the above mentioned id = "topicMessageListener" class = "com.yoodb.mq.topic.TopicMessageListener" /> 

<-! theme monitor container (topic) -> 
<bean the above mentioned id = " topicJmsContainer " 
    class =" org.springframework.jms.listener.DefaultMessageListenerContainer "> 
    <Property name =" The connectionFactory "REF =" The connectionFactory "/> 
    <Property name =" Where do you want "REF =" topicDestination "/> 
    <Property name =" messageListener "ref =" topicMessageListener "/>
</bean>
 

 

Post Owner code is as follows:

package com.yoodb.mq.topic;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class TopicProvider {
    private JmsTemplate topicJmsTemplate;
    /**
     * 向指定的topic发布消息
     * 
     * @param topic
     * @param msg
     */
    public void publish(final Destination topic, final String msg) {
        topicJmsTemplate.send(topic, new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            System.out.println("topic name 是" + topic.toString()
            + ",发布消息内容为:\t" + msg);
            return session.createTextMessage(msg);
        }
    });
    }
    public void setTopicJmsTemplate(JmsTemplate topicJmsTemplate) {
        this.topicJmsTemplate = topicJmsTemplate;
    }
}

 

News subscribers (listeners) code is as follows:

package com.yoodb.mq.topic;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
 *和队列监听的代码一样。
 */
public class TopicMessageListener implements MessageListener {
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
            System.out.println("TopicMessageListener \t" + tm.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

 

Test code is as follows:

com.yoodb.mq Package; 
Import a javax.jms.Destination; 
Import com.yoodb.mq.queue.ConsumerService; 
Import com.yoodb.mq.queue.ProducerService; 
Import com.yoodb.mq.topic.TopicProvider; 
Import ORG. junit.Test; 
Import org.junit.runner.RunWith; 
Import org.springframework.beans.factory.annotation.Autowired; 
Import org.springframework.beans.factory.annotation.Qualifier; 
Import org.springframework.test.context.ContextConfiguration; 
org.springframework.test.context.junit4.SpringJUnit4ClassRunner Import; 
/ ** 
 * test the JMS the Spring 
 * 
 * 1. producer sends a test message 
 * 
 * 2. test consumer acceptance message 
 * 
 * 3. test message listener 
 * 
 * 4. test theme monitor
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext context = new
// ClassPathXmlApplicationContext("applicationContext.xml");
@ContextConfiguration("/applicationContext.xml")
public class SpringJmsTest {
    /**
     * 队列名queue1
     */
    @Autowired
    private Destination queueDestination;
    
    /**
     * 队列名queue2
     */
    @Autowired
    private Destination queueDestination2;
    
    /**
     * 主题 guo_topic
     */
    @Autowired
    @Qualifier("topicDestination")
    private Destination topic;
    
    /**
     * Subject Post Owner 
     * / 
    @Autowired 
    Private TopicProvider topicProvider; 
    
    / ** 
     * queue message producer 
     * / 
    @Autowired 
    @ Qualifier ( "producerService") 
    Private ProducerService Producer; 
    
    / ** 
     * queue message producer 
     * / 
    @Autowired 
    @ Qualifier ( "consumerService") 
    Private consumerService Consumer; 
    
    / ** 
     * test sends a message to the producer Queue1 
     * / 
    @Test 
    public void testProduce () { 
    String MSG = "the Hello World!"; 
        producer.sendMessage (MSG); 
    } 
    
    / ** 
     * testing consumer acceptance message from the queue1
     * / 
    @Test 
    public void testConsume () { 
        consumer.receive (queueDestination); 
    } 
    
    / ** 
     * test message listener 
     * 
     * 1. producer sends a message queue queue2 
     * 
     * 2.ConsumerMessageListener monitor queue and a message consumer 
     * / 
    @ the test 
    public void testSend () { 
        producer.sendMessage (queueDestination2, "the Hello China !!!"); 
    } 
    
    / ** 
     * test theme listener 
     * 1. the producer released a message to the topic 
     * 2.ConsumerMessageListener listening to a topic and consume messages 
     * / 
    @Test 
    public void testTopic () throws Exception { 
        topicProvider.publish (Topic, "the Hello the To-T-Top-Topi-Topic!");
    }
}

 

Test results are as follows:

topic name is topic: // guo_topic, announced content:! the To-the Hello T-Top-Topi-Topic 
TopicMessageListener the To-the Hello T-Top-Topi-Topic! 
to queue queue: // queue2 sent a message ___Hello China !!! 
ConsumerMessageListener received a text message: Hello China !!! 
to queue queue: // queue1 sent a message ___Hello world! 
from the queue queue: // queue1 received the message: Hello world!

 

Other related articles Recommended:

ActiveMQ message queue from entry into practice (4) - Spring JMS messaging using

ActiveMQ message queue from entry into practice (3) - by sending and receiving messages ActiveMQ

ActiveMQ message queue from entry into practice (2) -Windows Service Installation activemq

ActiveMQ message queue from entry into practice (1) -JMS JMS messaging models and concepts

Guess you like

Origin www.cnblogs.com/MrYoodb/p/11877173.html