The ACTIVEMQ queue is full sending notifications to the message sender

Source: Internet
Author: User
Tags getmessage message queue uuid keep alive amq

Recently, the company is ready to use ACTIVEMQ to inform the message, and is request-reply mode, encountered a problem: when the producer to send messages to the queue, if the queue is full, you need to send a message to the producer, so as soon as possible to give users a reply, lest delay time, Since I have never been in touch with ACTIVEMQ, I can only learn while practicing. Today it is finally done, put the important code here, lest forget.

Content of Applicationcontext.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
	Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/conte Xt/spring-context-2.5.xsd "> <context:annotation-config/> <context:component-scan base-package=" ****.* . * * * */> <bean id= "Prefetchpolicy" class= "Org.apache.activemq.ActiveMQPrefetchPolicy" > <property na Me= "Queueprefetch" value= "1"/> </bean> <!--get connectionfctory from uri:tcp://localhost:61616--> & Lt;bean id= "ConnectionFactory" class= "org.apache.activemq.ActiveMQConnectionFactory" > <constructor-arg value = "tcp://localhost:61616"/> <property name= "AlwayssyncSend "value=" true "/> <property name=" producerwindowsize "value=" 0 "/> <property name=" Prefetchpolicy "ref = "Prefetchpolicy"/> </bean> <bean id= "pooledconnectionfactory" class= " Org.apache.activemq.pool.PooledConnectionFactory "destroy-method=" Stop "> <property name=" ConnectionFactory " ref= "ConnectionFactory"/> <property name= "maxconnections" value= ""/> <property "name=" MaximumActiveSes "  Sionperconnection "value="/> <property name= "expirytimeout" value= "ten"/> <property name= "IdleTimeout"


	value= "0"/> <!--<property name= "Timebetweenexpirationcheckmillis" value= "a"/>--> </bean> <bean id= "Classpathresource" class= "Org.springframework.core.io.ClassPathResource" > <constructor-arg Value= "Activemq.xml"/> </bean> <bean id= "Brokerfactory" Org.apache.activemq.xbean.BrokerFactoryBean "> <constructor-arg ref=" Classpathresource "/> <propertyName= "Start" value= "true"/> </bean> <!--queue for module demo--> <bean id= "queuedm" class= "ORG.A" Pache.activemq.command.ActiveMQQueue "> <property name=" physicalname "value=" queuedm "/> </bean> <! --N Multiple--> <!--<bean id= "AmqServer1" class= "****.******.****.demo.amq.amqserver" destroy-method= "Stop" >- > <!--<constructor-arg index= "0" ref= "pooledconnectionfactory"/>connection factory--> <!--<co Nstructor-arg index= "1" ref= "queuedm"/>queue--> <!--<constructor-arg index= "2" value= "a"/>thread cor E Pool Size--> <!--<constructor-arg index= "3" value= "30000"/>thread pool thread Keep alive time--> &L t;!  --<constructor-arg index= "4" value= "/>concurrent" task number--> <!--</bean>--> <bean Id= "Amqclient" class= "****.******.****.demo.amq.amqclient" scope= "prototype" > <property name= " Pooledconnectionfactory "ref=" PooledconnectIonfactory "/> <property name=" Adminqueue "ref=" queuedm "/> </bean> <bean id=" Mbeanchecker "class=" t Est.****.******.****.demo.amq.mbeanchecker "/> <bean id=" Messagesender "class=" test.****.******.****. Demo.amq.MessageSender "> <property name=" Client "ref=" Amqclient "/> </bean> </beans>

Activemq.xml Configuration file content:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Amq= "Http://activemq.apache.org/schema/core" 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-2.0.xsd Http://activemq.apache.org/schema/core Http://activemq.apache.org/schema/core/activemq-co Re.xsd "> <!--defines a broker, which is a activemq instance--> <amq:broker brokername=" Demobroker "xmlns=" HTTP://ACTIVEMQ " . Apache.org/schema/core "usejmx=" true "persistent=" false "> <amq:managementContext> <amq:managementcont Ext connectorport= "6161" jmxdomainname= "Demobrokercontext" connectorpath= "/jmxrmi"/> </amq:managementContext > <amq:systemUsage> <amq:systemusage sendfailifnospace= "true" > <amq:tempUsage> <amq : Tempusage limit= "0kb"/> </amq:tempUsage> <amq:memoryusage> <amq:memoryusage limit= "10kb"/> </amq:memoryUsage> <amq:storeUsage>

		<amq:storeusage limit= "0kb"/> </amq:storeUsage> </amq:systemUsage> </amq:systemUsage> <amq:destinationPolicy> <amq:policyMap> <amq:policyEntries> <amq:policyentry queue= "que
							UeDm "usecache=" false "memorylimit=" 10kb "producerflowcontrol=" true "> <amq:pendingQueuePolicy> <amq:vmqueuecursor/> </amq:pendingQueuePolicy> </amq:policyEntry> </amq:policyentrie s> </amq:policyMap> </amq:destinationPolicy> <amq:transportConnectors> <transportconnec Tor uri= "tcp://localhost:61616"/> </amq:transportConnectors> </amq:broker> </beans>


Message producer Amqclient.java Code:

Package ****.******.****.demo.amq;
Import Java.util.Date;

Import Java.util.UUID;
Import Javax.jms.DeliveryMode;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageConsumer;
Import Javax.jms.MessageListener;
Import Javax.jms.MessageProducer;
Import Javax.jms.ObjectMessage;

Import javax.jms.Session;
Import Org.apache.activemq.command.ActiveMQQueue;
Import org.apache.activemq.jms.pool.PooledSession;
Import org.apache.activemq.pool.PooledConnection;

Import Org.apache.activemq.pool.PooledConnectionFactory;
	
	public class Amqclient implements MessageListener {private pooledconnectionfactory pooledconnectionfactory;
	Public Pooledconnectionfactory Getpooledconnectionfactory () {return pooledconnectionfactory; } public void Setpooledconnectionfactory (Pooledconnectionfactory pooledconnectionfactory) {this.pooledconnectionf
	Actory = pooledconnectionfactory;
	Private Activemqqueue Adminqueue; Private MessageproducER producer;
	Private Messageconsumer consumer;
	
	Private destination Tempdest;
	Public Activemqqueue Getadminqueue () {return adminqueue;
	public void Setadminqueue (Activemqqueue adminqueue) {this.adminqueue = Adminqueue;
	Private Pooledconnection pconnection;
	
	Private Pooledsession psession; public void Start () throws jmsexception {pconnection = (pooledconnection) pooledconnectionfactory.createconnection ()
		;
		Pconnection.start ();
		Psession = (pooledsession) pconnection.createsession (false, Session.auto_acknowledge);
		Producer = Psession.createproducer (Adminqueue);
		Producer.setdeliverymode (deliverymode.non_persistent);
		Tempdest = Psession.createtemporaryqueue ();
		Consumer = Psession.createconsumer (tempdest);
		
	Consumer.setmessagelistener (this);
		public void Stop () throws JMSException {producer.close ();
		Consumer.close ();
		Psession.close ();
	Pconnection.close ();
		
		public void request (String request) throws JMSException {start (); SyStem.out.println ("Requesting:" + request);
		ObjectMessage objectmessage = Psession.createobjectmessage ();

		Objectmessage.setobject (Request);
		Objectmessage.setjmsreplyto (tempdest);
		Objectmessage.setjmstimestamp (New Date (). GetTime ());
		String Correlationid = Uuid.randomuuid (). toString ();
		Objectmessage.setjmscorrelationid (Correlationid);
	Producer.send (ObjectMessage); @Override public void onMessage (message message) {try {System.out.println (objectmessage) message). GetObject ()
		);
		catch (JMSException e) {System.out.println (E.getmessage ());
 }
	}
}


Tool class to view queue information: Mbeanchecker.java

Package test.****.******.****.demo.amq;
Import javax.management.MBeanServerConnection;
Import Javax.management.MBeanServerInvocationHandler;
Import Javax.management.ObjectName;
Import Javax.management.remote.JMXConnector;
Import Javax.management.remote.JMXConnectorFactory;

Import Javax.management.remote.JMXServiceURL;
Import Org.apache.activemq.broker.jmx.BrokerViewMBean;

Import Org.apache.activemq.broker.jmx.QueueViewMBean; public class Mbeanchecker {public Mbeanchecker () {New Thread ()} {public void run () {try {Thread.Sleep
					(20000);
						for (int i = 0; I < 10000 i++) {thread.sleep (1200);
					Check ();
				} catch (Exception e) {e.printstacktrace (); 
		}
			};
	}.start (); private void Check () throws Exception {jmxserviceurl url = new Jmxserviceurl ("Service:jmx:rmi:///jndi/rmi://localh
		Ost:6161/jmxrmi ");
		Jmxconnector connector = jmxconnectorfactory.connect (URL, null);
		Connector.connect (); Mbeanserverconnection Connection= Connector.getmbeanserverconnection (); It is important to note that the My-broker must be the same as the name when the Broker was defined/** * Org.apache.activemq:brokername=localhost,type=broker * Brokernam
		 E and type must be first lowercase * org.apache.activemq:brokername=localhost,type=broker uppercase small sensitive.
		* * ObjectName name = new ObjectName ("Demobrokercontext:brokername=demobroker,type=broker"); Brokerviewmbean MBean = (brokerviewmbean) mbeanserverinvocationhandler.newproxyinstance (connection, name,
		Brokerviewmbean.class, True);
		System.out.println (Mbean.getbrokername ()); for (objectname queueName:mBean.getQueues ()) {Queueviewmbean Queuembean = (Queueviewmbean) mbeanserverinvocationhand
			Ler.newproxyinstance (Connection, QueueName, Queueviewmbean.class, true);
			System.out.println ("\ n------------------------------\ n");
			States for queue System.out.println ("Message Queue name:---" + queuembean.getname ());
			Size System.out.println ("Number of messages remaining in the queue:---" + queuembean.getqueuesize ()); Number of consumers:System.out.println ("consumptionNumber of persons:---"+ queuembean.getconsumercount ());
		Number of DEQUEUE:SYSTEM.OUT.PRINTLN ("Out of queue:---" + queuembean.getdequeuecount ());
 } public static void Main (string[] args) {}}

Test the class that sent the message: Messagesender.java


Package test.****.******.****.demo.amq;

Import javax.jms.JMSException;

Import Org.springframework.web.context.ContextLoader;

Import ****.******.****.demo.amq.amqclient;
	
	public class Messagesender {private amqclient client;
	Public Amqclient getclient () {return client;
	public void Setclient (Amqclient client) {this.client = client;
				Public Messagesender () {new Thread () {public void run () {try {thread.sleep (20000)};
				catch (Interruptedexception e) {e.printstacktrace ();
			} sendrequest ();
		};
	}.start ();
			private void SendRequest () {for (int i = 0; i < 5000; i++) {try {thread.sleep (200);
			catch (Interruptedexception E1) {e1.printstacktrace ();
				try {amqclient client = (amqclient) contextloader.getcurrentwebapplicationcontext (). Getbean ("Amqclient");
				Client.request ("test-request:" + i);
			SYSTEM.OUT.PRINTLN ("Test-side Send message: test-request:" + i); catch (JMSException e) {System.err.priNTLN ("error message obtained by JZF sender ====================================" + e.getmessage ());
			Break
 }} public static void Main (string[] args) {}}




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.