JMS Learning 11 (SPRING+ACTIVEMQ message Persistence, topic persistent subscription) __JMS

Source: Internet
Author: User
Tags aop

Message persistence is the benefit of saving messages to disk, and the advantage is that if the service is dead, the message is saved on the disk, and the message is sent to the server, and the message's persistence is not related to the sending model of the message.

The message persistence configuration is convenient, so the other ones are not written, and you can look at the synchronous asynchronous implementations in the previous article. This only lists the persistent configurations.

<!--Spring uses Jmstemplate to deliver and accept messages-->
	<bean id= "jmstemplate" class= " Org.springframework.jms.core.JmsTemplate ">
		<property name=" ConnectionFactory "ref=" ConnectionFactory " ></property>
		<property name= "defaultdestination" ref= "Destination" ></property>
		< Property name= "Messageconverter" >
			<bean
				class= " Org.springframework.jms.support.converter.SimpleMessageConverter "/>
		</property>
		 <!-- Open Subscription mode-->
		 <property name= "Pubsubdomain" value= "false"/> <property "name=
		 " Sessionacknowledgemode "value=" 1 "/> 
		  <!--deliverymode, priority, timetolive switch, to be effective, Explicitqosenabled must be configured to True, the default false-->
		 <property name= "explicitqosenabled" value= "true"/>
         <!--send mode  deliverymode.non_persistent=1: not durable; deliverymode.persistent=2: Persistent-->    
         <property name= "DeliveryMode" value= "2"/>
	</bean>

The message persistence configuration, as above, is persisted to the database or file or is configured in the activemq.xml of the messaging service.

The persistence of the OK message that's it. Let's take a look at the implementation of topic's theme persistence subscription.

Topic Message Persistence Subscription

Through the previous study we know that the message of the persistent subscription requirements: (1), Message persistence (2), message consumer to specify ClientID, at the same time only one clientid the same consumer connection consumption, so if there are multiple consumers, then ClientID can not be the same. Let's take a look here.

The project structure is as follows:


Project Structure Introduction:

1, a message producer, two message consumers and a listener class is Mymessagelistener.java, the same as the asynchronous processing of messages and heavy activemq.

2, three profiles are the message producer's configuration file and the message consumer's profile.

The other is related to the previous relevant demo here on the above 1, 2 mentioned in the related things.

Actually something really little, let's take a look at the code:

1, the message producer configuration file is applicationcontext3p.xml configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:task= "Http://www.springframework.org/schema/task" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframe Work.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.spring FRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd H
				 Ttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd Http://www.springframework.org/schema/tx Http://www.springfraMework.org/schema/tx/spring-tx-3.2.xsd "> <!--third Party factory--> <bean id=" targetconnectionfactory "class=" Org.apache.activemq.ActiveMQConnectionFactory "> <property name=" brokerurl "value=" tcp://127.0.0.1:61616 " > <property name= "userName" value= "admin" ></property> <property name= "password" value= "admin" >& lt;/property> <property name= "Useasyncsend" value= "true"/> </bean> <!--ACTIVEMQ provides us with a pooledconn Ectionfactory, by injecting a activemqconnectionfactory into the inside can be used to connection, session and MessageProducer pool, which can greatly reduce our resource consumption, To rely on the Activemq-pool package--> <bean id= "Pooledconnectionfactory" Org.apache.activemq.pool.PooledConnectionFactory "> <property name=" connectionfactory "ref=" Targetconnectionfactory "/> <property name=" maxconnections "value="/> </bean> <!--spring for managing True Positive connectionfactory connectionfactory--> <bean id= "ConnectionFactory" Org.springframework.jms.connection.SingleCOnnectionfactory "> <!--target connectionfactory corresponds to the real connectionfactory--> <property that can produce JMS connection name= "Targetconnectionfactory" ref= "Pooledconnectionfactory"/> </bean> <!--topic destination configuration, In fact, whether it's topic or queue, their underlying implementations are different, but they're pretty much the same through encapsulation APIs, and in spring it's simpler--> <bean id= "Destinationtopic" class= " Org.apache.activemq.command.ActiveMQTopic "> <constructor-arg index=" 0 "value=" spring-topic "/> </bean > <!--Spring uses Jmstemplate to deliver and accept messages--> <bean id= "Jmstemplate" class= Template "> <property name=" connectionfactory "ref=" ConnectionFactory "></property> <property name= "Defaultdestination" ref= "Destinationtopic" ></property> <!--for persistent--> <property name= " 
DeliveryMode "value=" 2/> <!--Open Subscription mode--> <property name= "Pubsubdomain" value= "true"/> </bean> </beans>

2. Message Producer:

Package springs.activemq.Service;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import javax.jms.Session;

Import Javax.jms.TextMessage;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Org.springframework.jms.core.JmsTemplate;

Import Org.springframework.jms.core.MessageCreator; 
	/** * @author Administrator */public class Queueproducer {//responsible for sending and receiving messages can be understood as a combination of messageproducer and Messageconsummer.

	private static jmstemplate JT = NULL; public static void Main (string[] args) {ApplicationContext ctx = new Classpathxmlapplicationcontext ("Config/applic
		Ationcontext3p.xml ");
		Get Jmstemplate Object JT = (jmstemplate) ctx.getbean ("Jmstemplate"); Call the method, send the message jt.send (new Messagecreator () {//The generation of the message, return the message to send the message to public messages CreateMessage (session s) throws Jmsex
				ception {textmessage msg = S. Createtextmessage ("Spring send msg----> Hello activeMQ3"); Return msg;
		}
		});
	System.out.println ("end!");
 }
}

3, the message consumer 1 of the configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:task= "Http://www.springframework.org/schema/task" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframe Work.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.spring FRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd H
				 Ttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd Http://www.springframework.org/schema/tx Http://www.springfraMework.org/schema/tx/spring-tx-3.2.xsd "> <!--third Party factory--> <bean id=" targetconnectionfactory "class=" Org.apache.activemq.ActiveMQConnectionFactory "> <property name=" brokerurl "value=" tcp://127.0.0.1:61616 " > <property name= "userName" value= "admin" ></property> <property name= "password" value= "admin" >& lt;/property> <property name= "Useasyncsend" value= "true"/> </bean> <!--ACTIVEMQ provides us with a pooledconn Ectionfactory, by injecting a activemqconnectionfactory into the inside can be used to connection, session and MessageProducer pool, which can greatly reduce our resource consumption, To rely on the Activemq-pool package--> <bean id= "Pooledconnectionfactory" Org.apache.activemq.pool.PooledConnectionFactory "> <property name=" connectionfactory "ref=" Targetconnectionfactory "/> <property name=" maxconnections "value="/> </bean> <!--spring for managing True Positive connectionfactory connectionfactory--> <bean id= "ConnectionFactory" Org.springframework.jms.connection.SingleCOnnectionfactory "> <!--Consumer ID--> <property name=" clientId "value=" clientid_001 "/> <!--target Connec Tionfactory corresponds to the real connectionfactory--> <property name= "targetconnectionfactory" that can produce JMS connection Pooledconnectionfactory "/> </bean> <!--topic destination configuration, in fact, whether topic or queue, their low-level implementation is different but through the encapsulation API is almost, And in spring, it's simpler--> <bean id= "Destinationtopic" class= "Org.apache.activemq.command.ActiveMQTopic" > < Constructor-arg index= "0" value= "spring-topic"/> </bean> <!--message Consumer listener class--> <bean id= "Mymessagelisten
		Er "class=" Springs.activemq.Service.MyMessageListener "/> <!--monitoring container configuration--> <bean id=" Mylistenercontainer " class= "Org.springframework.jms.listener.DefaultMessageListenerContainer" > <property name= " ConnectionFactory "ref=" ConnectionFactory "/> <!--message destination--> <property name=" Destination "ref=" Topic "/> <!--message Listener class--> <property name=" MessageListener "ref=" MymeSsagelistener "/> <!--Publish subscription mode--> <property name=" Pubsubdomain "value=" true "/> <!--message persistence value set to True --> <property name= "subscriptiondurable" value= "true"/> <!--message receive timeout--> <property name= "ReceiveTi  Meout "value=" 10000/> <!--recipient ID--> <property name= "clientId" value= "clientid_001"/> <property
 Name= "Durablesubscriptionname" value= "clientid_001"/> </bean> </beans>

4, the message consumer 2 of the configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:task= "Http://www.springframework.org/schema/task" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframe Work.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.spring FRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd H
				 Ttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd Http://www.springframework.org/schema/tx Http://www.springfraMework.org/schema/tx/spring-tx-3.2.xsd "> <!--third Party factory--> <bean id=" targetconnectionfactory "class=" Org.apache.activemq.ActiveMQConnectionFactory "> <property name=" brokerurl "value=" tcp://127.0.0.1:61616 " > <property name= "userName" value= "admin" ></property> <property name= "password" value= "admin" >& lt;/property> <property name= "Useasyncsend" value= "true"/> </bean> <!--ACTIVEMQ provides us with a pooledconn Ectionfactory, by injecting a activemqconnectionfactory into the inside can be used to connection, session and MessageProducer pool, which can greatly reduce our resource consumption, To rely on the Activemq-pool package--> <bean id= "Pooledconnectionfactory" Org.apache.activemq.pool.PooledConnectionFactory "> <property name=" connectionfactory "ref=" Targetconnectionfactory "/> <property name=" maxconnections "value="/> </bean> <!--spring for managing True Positive connectionfactory connectionfactory--> <bean id= "ConnectionFactory" Org.springframework.jms.connection.SingleCOnnectionfactory "> <!--Consumer ID--> <property name=" clientId "value=" clientid_002 "/> <!--target Connec Tionfactory corresponds to the real connectionfactory--> <property name= "targetconnectionfactory" that can produce JMS connection Pooledconnectionfactory "/> </bean> <!--topic destination configuration, in fact, whether topic or queue, their low-level implementation is different but through the encapsulation API is almost, And in spring, it's simpler--> <bean id= "Destinationtopic" class= "Org.apache.activemq.command.ActiveMQTopic" > < Constructor-arg index= "0" value= "spring-topic"/> </bean> <!--message Consumer listener class--> <bean id= "Mymessagelisten
		Er "class=" Springs.activemq.Service.MyMessageListener "/> <!--monitoring container configuration--> <bean id=" Mylistenercontainer " class= "Org.springframework.jms.listener.DefaultMessageListenerContainer" > <property name= " ConnectionFactory "ref=" ConnectionFactory "/> <!--message destination--> <property name=" Destination "ref=" Topic "/> <!--message Listener class--> <property name=" MessageListener "ref=" mymessAgelistener "/> <!--Publish subscription mode--> <property name=" Pubsubdomain "value=" true "/> <!--message persistence value set to true- -> <property name= "subscriptiondurable" value= "true"/> <!--message receive timeout--> <property name= "ReceiveTime Out "value=" 10000 "/> <!--recipient ID--> <property name=" clientId "value=" clientid_002 "/> <property N

 Ame= "Durablesubscriptionname" value= "clientid_002"/> </bean> </beans>

5, consumer 1 namely Simplejmsreceiver.java

Package springs.activemq.Service;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
public class Simplejmsreceiver {public
    static void Main (string[] args) {  
        ApplicationContext ctx = new CLASSPATHXM Lapplicationcontext ("Config/applicationcontext3c.xml");  
        while (true) {  
        }  
    }  
}

6, News consumer 2simplejmsreceiver2.java

Package springs.activemq.Service;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
public class SimpleJMSReceiver2 {public
    static void Main (string[] args) {  
        ApplicationContext ctx = new Classpathx Mlapplicationcontext ("Config/applicationcontext3c2.xml");  
        while (true) {  
        }  
    }  
   
}

7, Message listening class

Package springs.activemq.Service;

Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageListener;
Import Javax.jms.TextMessage;

public class Mymessagelistener implements MessageListener {public
	void onMessage (message arg0) {
		//TODO Auto-ge nerated method Stub
		try {
			String message = ((TextMessage) arg0). GetText ();
			System.out.println ("TextMessage:" + message);
		} catch (JMSException e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		}
	}

}
The parameter of the OnMessage method of the message listener class is the received message, and we do business processing of the message in the method.


OK, here's the persistent subscription to the message OK, simply say:

1. Topic Message Persistence Subscriptions need to persist messages, either to the file or to the database, looking at the persistent configuration in Activemq.xml in the message server, and whether the message to be persisted needs to be configured "DeliveryMode" in Jmstemplate The value is 2.

2, the message consumer to set the ClientID identifier, so as to know who.

3, the message listener class, this class is to process the message, in the actual project to use synchronization should not be much, it should be the configuration of listening classes, such as this demo our listening class used the same, but in the project if there are different requirements we can define each of the consumer monitoring class to do the specific processing.

OK here it's over, you can start message producer production messages, persist into the database, and then start consumer 1 and consumer news, you can see two consumers can get the message. When you look at the database then the messages in the database are gone.


Execution results:

1. Message producer:



2, the message persisted to the MySQL database:



3, start consumer 1:


4, Start consumer 2


Ok so the whole process is gone, when the message is sent to the message service, if the service is dead, you start the message service and then start the message consumers, then you can still get the information not consumed. This also satisfies our persistent subscription.

SOURCE download: Click to open the link

Reference articles:

http://blog.csdn.net/s296850101/article/details/52382720

http://greemranqq.iteye.com/blog/2167158

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.