ACTIVEMQ uses thread pooling to achieve message production and consumption

Source: Internet
Author: User
Tags getmessage sendmsg sessions

1. First introduce the related LIB package, Key need to refer to Activemq-client-5.8.0.jar,activemq-core-5.7.0.jar,activemq-pool-5.8.0.jar,activemq-protobuf-1.1.jar and other packages

Self-configuring.


2. Code for some common utility classes:

Jmsproducer.java

Package COM.FFCS.ICITY.JMS;
Import Java.util.Map;
Import Java.util.Set;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors;
Import javax.jms.Connection;
Import Javax.jms.DeliveryMode;
Import javax.jms.Destination;
Import Javax.jms.ExceptionListener;
Import javax.jms.JMSException;
Import Javax.jms.MapMessage;
Import Javax.jms.Message;
Import Javax.jms.MessageProducer;

Import javax.jms.Session;
Import Org.apache.activemq.ActiveMQConnectionFactory;

Import Org.apache.activemq.pool.PooledConnectionFactory; /** * JMS Message producer * @author Linwei * * */public class Jmsproducer implements exceptionlistener{//set maximum number of connections public fi
	nal static int default_max_connections=5;
	private int maxconnections = default_max_connections;
	Set the maximum number of active sessions used in each connection private int maximumactivesessionperconnection = default_maximum_active_session_per_connection;
	Public final static int default_maximum_active_session_per_connection=300; Number of thread pools private int threadpoolsize = DefaulT_thread_pool_size;
	Public final static int default_thread_pool_size=50;
	Force a format to return data using synchronization private Boolean USEASYNCSENDFORJMS = DEFAULT_USE_ASYNC_SEND_FOR_JMS;
	Public final static Boolean default_use_async_send_for_jms=true;
	Whether to persist the message private Boolean ispersistent = Default_is_persistent; 
	
	Public final static Boolean default_is_persistent=true;

	Connection address private String Brokerurl;

	Private String UserName;

	private String password;

	Private Executorservice ThreadPool;

	Private Pooledconnectionfactory connectionfactory; Public Jmsproducer (String brokerurl, String userName, string password) {This (Brokerurl, userName, password, Default_max _connections, Default_maximum_active_session_per_connection, Default_thread_pool_size, DEFAULT_USE_ASYNC_SEND_FOR
	_JMS, default_is_persistent); Public Jmsproducer (String brokerurl, String userName, string password, int maxconnections, int maximumactivesessionpe rconnection, int Threadpoolsize,boolean useasyncsendforjms, Boolean ispersistENT) {this.useasyncsendforjms = USEASYNCSENDFORJMS;
		This.ispersistent = ispersistent;
		This.brokerurl = Brokerurl;
		This.username = UserName;
		This.password = password;
		This.maxconnections = MaxConnections;
		This.maximumactivesessionperconnection = maximumactivesessionperconnection;
		This.threadpoolsize = ThreadPoolSize;
	Init ();
		private void Init () {//Set Java thread pool This.threadpool = Executors.newfixedthreadpool (this.threadpoolsize); ACTIVEMQ's Connection factory activemqconnectionfactory actualconnectionfactory = new Activemqconnectionfactory (This.username,
		This.password, This.brokerurl);
		Actualconnectionfactory.setuseasyncsend (THIS.USEASYNCSENDFORJMS);
		Connection pool factory in active this.connectionfactory = new Pooledconnectionfactory (actualconnectionfactory);
		This.connectionFactory.setCreateConnectionOnStartup (TRUE);
		This.connectionFactory.setMaxConnections (this.maxconnections); This.connectionFactory.setMaximumActiveSessionPerConnection (this.maximumactivesessionperconnectiON);  /** * Executes the specific method of sending the message * @param queue * @param map/public void Send (final String queue, final map<string, Object> map) {//direct use of the thread pool to perform specific calls This.threadPool.execute (new Runnable () {@Override public void run () {T
				ry {sendmsg (queue,map);
				catch (Exception e) {e.printstacktrace ();
	}
			}
		}); /** * True Execution message send * @param queue * @param map * @throws Exception/private void sendmsg (String queue, map& Lt
		String, object> map) throws Exception {Connection Connection = null;
		Session session = NULL;
			try {//Get a connection from the connection pool factory connection = This.connectionFactory.createConnection (); /*createsession (Boolean transacted,int acknowledgemode) transacted-indicates Whether the session is transacted ACKN Owledgemode-indicates whether the consumer or the client would acknowledge any messages it receives; 
			  Ignored if is transacted. Legal values are Session.auto_acknowledge, Session.clienT_acknowledge, and Session.dups_ok_acknowledge.
			The///false parameter is represented as a non transactional message, and the following parameter represents the acknowledgment type of the message session = Connection.createsession (Boolean.false, Session.auto_acknowledge);
			Destination is superinterface of Queue//PTP message way Destination Destination = Session.createqueue (queue); Creates a messageproducer to send messages to the specified destination messageproducer producer = Session.createpro
			Ducer (destination); Set Delevery mode Producer.setdeliverymode (this.ispersistent?)
			DeliveryMode.PERSISTENT:DeliveryMode.NON_PERSISTENT);
			Map Convert to javax message message = GetMessage (session, map);
		Producer.send (message);
			finally {closesession (session);
		CloseConnection (connection); } private Message GetMessage (sessions session, Map<string, Object> Map) throws JMSException {Mapmessage mess
		Age = Session.createmapmessage ();
			if (map!= null &&!map.isempty ()) {set<string> keys = Map.keyset (); for (StRing Key:keys) {Message.setobject (key, Map.get (key));
	} return message;
			private void CloseSession {try {if (session!= null) {session.close ();
		} catch (Exception e) {e.printstacktrace ();
			} private void CloseConnection (Connection Connection) {try {if (Connection!= null) {connection.close ();
		} catch (Exception e) {e.printstacktrace ();
	@Override public void Onexception (JMSException e) {e.printstacktrace ();
 }

}

Jmsconsumer.java

Package COM.FFCS.ICITY.JMS;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
Import javax.jms.Destination;
Import Javax.jms.ExceptionListener;
Import javax.jms.JMSException;
Import Javax.jms.MessageConsumer;
Import Javax.jms.MessageListener;

Import javax.jms.Session;
Import org.apache.activemq.ActiveMQConnection;
Import Org.apache.activemq.ActiveMQConnectionFactory;


Import Org.apache.activemq.ActiveMQPrefetchPolicy; /** * JMS Message consumer * @author Linwei * */public class Jmsconsumer implements Exceptionlistener {//queue prefetch policy private int Q
	Ueueprefetch=default_queue_prefetch;
	
	Public final static int default_queue_prefetch=10;
	
	Private String Brokerurl;

	Private String UserName;

	private String password;
	
	Private MessageListener MessageListener;
	
	Private Connection Connection;
	Private session session;
	
	
	Queue name private String queue;  /** * Perform message acquisition operation * @throws Exception/public void Start () throws Exception {//ACTIVEMQ Connection factory connectionfactory CoNnectionfactory = new Activemqconnectionfactory (This.username, This.password, This.brokerurl);
		Connection = Connectionfactory.createconnection ();
		ACTIVEMQ pre-fetching strategy Activemqprefetchpolicy Prefetchpolicy = new Activemqprefetchpolicy ();
		Prefetchpolicy.setqueueprefetch (Queueprefetch);
		((activemqconnection) connection). Setprefetchpolicy (Prefetchpolicy);
		Connection.setexceptionlistener (this);
		Connection.start ();
		The session takes a non transactional level, and the message arrival mechanism uses the automatic notification mechanism to connection.createsession (Boolean.false, Session.auto_acknowledge);
		Destination Destination = Session.createqueue (This.queue);
		Messageconsumer consumer = session.createconsumer (destination);
	Consumer.setmessagelistener (This.messagelistener);
				/** * Close connection */public void shutdown () {try {if (session!= null) {session.close ();
			Session=null;
				} if (connection!= null) {connection.close ();
			Connection=null;
		} catch (Exception e) {e.printstacktrace (); }} @Override public voidOnexception (jmsexception e) {e.printstacktrace ();
	Public String Getbrokerurl () {return brokerurl;
	} public void Setbrokerurl (String brokerurl) {this.brokerurl = Brokerurl;
	Public String GetUserName () {return userName;
	} public void Setusername (String userName) {this.username = UserName;
	Public String GetPassword () {return password;
	} public void SetPassword (String password) {this.password = password;
	Public String Getqueue () {return queue;
	public void Setqueue (String queue) {this.queue = queue;
	Public MessageListener Getmessagelistener () {return messagelistener;
	public void Setmessagelistener (MessageListener messagelistener) {this.messagelistener = MessageListener;
	public int Getqueueprefetch () {return queueprefetch;
	The public void Setqueueprefetch (int queueprefetch) {this.queueprefetch = Queueprefetch;
 }
	
	
}

Messagehandler.java

Package COM.FFCS.ICITY.JMS;

Import Javax.jms.Message;


/**
 * Provides a callback interface for message operations
 * @author Linwei
 * */public
interface MessageHandler {

	
	/**
	 * The invocation method provided by the message callback
	 * @param messages
	 /public
	void handle


Multithreadmessagelistener.java

Package COM.FFCS.ICITY.JMS;

Import Java.util.concurrent.ExecutorService;
Import Javax.jms.Message;


Import Javax.jms.MessageListener;

	/** * The multithreaded message listening service used in the message consumer * @author Linwei */public class Multithreadmessagelistener implements MessageListener {
	Default thread pool number public final static int default_handle_thread_pool=10;
	The maximum number of processing threads.
	private int maxhandlethreads;

	Provides a message callback call interface private MessageHandler MessageHandler;
	
	
	Private Executorservice Handlethreadpool; Public Multithreadmessagelistener (MessageHandler MessageHandler) {This (Default_handle_thread_pool, MessageHandler)
	; Public Multithreadmessagelistener (int maxhandlethreads,messagehandler messagehandler) {this.maxhandlethreads=
		Maxhandlethreads;
		This.messagehandler=messagehandler;
	Supports blocked, fixed-size thread pools (manually created by themselves) This.handlethreadpool = new Fixedandblockedthreadpoolexecutor (this.maxhandlethreads); /** * The method that is invoked automatically in the * listener * * * @Override public void OnMessage (final message) {/////using a blocked, fixed size thread pool to perform operations thIs.handleThreadPool.execute (New Runnable () {public void run () {try {MultiThreadMessageListener.this.message
				Handler.handle (message);
				catch (Exception e) {e.printstacktrace ();
	}
			}
		});
 }

}

Fixedandblockedthreadpoolexecutor.java

Package COM.FFCS.ICITY.JMS;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.ThreadPoolExecutor;
Import Java.util.concurrent.TimeUnit;
Import java.util.concurrent.locks.Condition;


Import Java.util.concurrent.locks.ReentrantLock;

	
	/** * supports blocked fixed size thread pools * @author Linwei * */public class Fixedandblockedthreadpoolexecutor extends Threadpoolexecutor {
	A reentrant mutex lock that has the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and statement, but is more powerful.
	
	Use the lock block to invoke try, and the private reentrantlock lock = new Reentrantlock () in the previous/subsequent construct;
	
	Private Condition Condition = This.lock.newCondition (); public fixedandblockedthreadpoolexecutor (int size) {Super (size, size, 0L, timeunit.milliseconds, new Linkedblockingque
	Ue<runnable> ());
	 /** * The calling thread of this method is suspended when there is no idle thread in the thread pool. The thread has a thread in it.
		*/@Override public void Execute (Runnable command) {//Synchronous lock This.lock.lock ();
		Super.execute (command); try {//If the number of thread pools has reached the maximum number of thread pools, suspend exerciseAs if (getpoolsize () = = Getmaximumpoolsize ()) {this.condition.await ();
		} catch (Interruptedexception e) {e.printstacktrace ();
		finally {This.lock.unlock ();
		} @Override protected void AfterExecute (Runnable R, Throwable t) {Super.afterexecute (r, T);
			try {this.lock.lock ();
		This.condition.signal ();
		finally {This.lock.unlock ();
 }
	}
	
	
}


3. Call Example Description:

Producer calling code, Jmsproducertest.java

Package com.ffcs.icity.test;

Import Java.util.HashMap;
Import Java.util.Map;

Import Com.ffcs.icity.jms.JMSProducer;

public class Jmsproducertest {public

	
	static void Main (string[] args) {
		
		locationtest ();
		System.out.println ("over.");
	}
	
	The private static void Locationtest () {
		//**  jmsproducer can be set as a global static variable, only to be instantiated once and to prevent the recurrence of repeated instantiations jmsproducer ( Because there is a thread pool within it
		
		//support the default connection for the Openwire protocol is tcp://localhost:61616, the default connection for the STOMP protocol is tcp://localhost:61613. 
		the difference between//tcp and NiO
		//nio://localhost:61617 and tcp://localhost:61616 can be configured
		in Activemq.xml configuration files Jmsproducer producer = new Jmsproducer ("nio://localhost:61617", "System", "Manager");
		map<string, object> map = new hashmap<string, object> ();
		Map.put ("id", "1");
		Map.put ("name", "sss1113333");
		Map.put ("Password", "password");
		Producer.send ("Test", map);
	}
	


Consumer calling code, Jmsconsumertest.java

Package com.ffcs.icity.test;
Import Javax.jms.MapMessage;

Import Javax.jms.Message;
Import Com.ffcs.icity.jms.JMSConsumer;
Import Com.ffcs.icity.jms.MessageHandler;

Import Com.ffcs.icity.jms.MultiThreadMessageListener; public class Jmsconsumertest {public static void main (string[] args) throws Exception {//** Jmsconsumer can be set up
		The static variables of the bureau can be used only once, to prevent cyclic recurrence of jmsconsumer (because there is a thread pool within it) jmsconsumer consumer = new Jmsconsumer ();
		Consumer.setbrokerurl ("tcp://localhost:61616");
		Consumer.setqueue ("test");
		Consumer.setusername ("system");
		Consumer.setpassword ("manager");
		Consumer.setqueueprefetch (500); Consumer.setmessagelistener (New Multithreadmessagelistener (50,new MessageHandler () {public void handle
					Message) {try {System.out.println (' name is ' + (mapmessage) message). GetString (' name ');
				Thread.Sleep (5000);
				catch (Exception e) {e.printstacktrace ();
		}
			}
		}));
		
Consumer.start ();
Thread.Sleep (5000); Consumer.sHutdown ();
 }
	
	
}





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.