Active MQ Use
Kagula
2011-9-6 Introduction
Active MQ is a message Queue manager, a middleware for communication.
There are two common ways to use Java + Active MQ: [1] Point-to-Point mode (Producer/consumer) [2] Publish/Subscriber mode (Publisher/subscriber Model)
test environment [1]jdk1.6.x [2]eclipse Indigo [3]active MQ 5.4.2
It is recommended that you do not use active MQ 5.5.0 because Activemq-all-5.5.0.jar is missing dependencies. Body
Reference [1] ensures that active MQ is installed and started correctly.
point to Point (Producer, Consumer) mode
Figure one JMS object model
Producer End Source Example
Import org.apache.activemq.ActiveMQConnection;
Import Org.apache.activemq.ActiveMQConnectionFactory;
Import javax.jms.*; /** * Message producer (sender) */public class Jmssender {public static void main (string[] args) throws Jmsexcept Ion {//ConnectionFactory: Connect factory, JMS use it to create connection connectionfactory connectionfactory = NE
W Activemqconnectionfactory (Activemqconnection.default_user,
Activemqconnection.default_password, "failover://(tcp://127.0.0.1:61616)"); JMS Client to JMS Provider connection Connection Connection = Connectionfactor
Y.createconnection ();
Connection.start (); Session: The first parameter of a thread//createsession that sends or receives messages Boolean.false refers to the current session is not a transaction// That is, the message is autocommit, you can't call Session.commIt functions commit transactions. CreateSession's first argument boolean.true refers to the newly created session is a transaction//You must call the Session.commit function to commit the transaction before the message can really be
Put to queue Server session session = Connection.createsession (Boolean.true, Session.auto_acknowledge);
Destination: The destination of the message, and to whom the message is sent.
Get session Note parameter value My-queue is the name of query destination Destination = Session.createqueue ("My-queue"); MessageProducer: Message producer MessageProducer producer = Session.createproducer (des
Tination);
Set the Producer.setdeliverymode (deliverymode.non_persistent);
Send a message sendmsg (session, producer);
Connection.close (); /** * on the specified session, a message is sent through the specified message producer * * @param session message Sessions * @p
Aram Producer Message Producer */public static void Sendmsg (Sessions session, MessageProducer producer) throws JMSException { Creates a text message textmessage messages = Session.createtextmessage ("Hello ActiveMQ.")
");
Messages are sent through the message producer Producer.send (message);
System.out.println (""); }
}
Consumer End Source Example
Import org.apache.activemq.ActiveMQConnection;
Import Org.apache.activemq.ActiveMQConnectionFactory;
Import javax.jms.*; public class Jmsreceiver {public static void main (string[] args) throws JMSException {//C
Onnectionfactory: Connect factory, JMS use it to create connection connectionfactory connectionfactory = new Activemqconnectionfactory ( Activemqconnection.default_user, Activemqconnection.
Default_password, "tcp://127.0.0.1:61616");
JMS Client to JMS Provider connection Connection Connection = Connectionfactory.createconnection ();
Connection.start (); Session: The first parameter of a thread//createsession that sends or receives messages Boolean.false refers to the current session is not a transaction//
That is, the message is automatically committed or received, you cannot call the Session.commit function to commit the transaction. The first parameter of the CreateSession boolean.trThe UE refers to the newly created session as a transaction//You must call the Session.commit function to commit the transaction, otherwise the received message is still in/
Queue Server, you receive one more time and find them still.
Session session = Connection.createsession (Boolean.true, Session.auto_acknowledge);
Destination: The destination of the message, from which queue the message is received.
Destination Destination = Session.createqueue ("My-queue");
Consumer, message receiver Messageconsumer consumer = session.createconsumer (destination); while (true) {///1 seconds did not receive a message, that is, return textmessage messages = (TextMessage) cons
Umer.receive (1000);
if (null!= message) SYSTEM.OUT.PRINTLN ("Received:" + message.gettext ());
else break;
} session.commit ();
Session.close (); ConnecTion.close (); }
}
Publisher/subscriber Model
Message propagation is delivered in one-to-many relationships--A publisher, multiple subscriber.
You can also add the following code for the following source example
Topicpublisher.setdeliverymode (deliverymode.persistent);
Its role is: ACTIVEMQ server reboot, still keep the message you sent up.
You can also use the following code snippet to set the lifetime of messages sent up on the MQ server
Topicpublisher.settimetolive (1000*60*60*24*3);//ms as Unit
Source code Example
public class Sampleutilities {
static public class Donelatch {
Boolean done = false;
/**
* Waits until was set to true.
/public void Waittilldone () {
synchronized (a) {while
(! Done) {
try {
this.wait ();
} catch (Interruptedexception IE) {}}}
/** * Sets done to
true.
*
/public void Alldone () {
synchronized (this) {done
= true;
This.notify ();}}}
Import Java.util.Date;
Import javax.jms.*;
Import org.apache.activemq.ActiveMQConnection;
Import Org.apache.activemq.ActiveMQConnectionFactory; /** * @author Kim Haase * @comment &modified by Kagula * @version 1.6, 08/18/00 * @lastUpdateDate 09/06/11/Pub
Lic class Asynchtopicexample {final String control_queue = "Controlqueue";
String topicname = null;
int exitresult = 0; public static ConnectionFactory Getjmsconnectionfactory () throws jmsexception {String user = ActiveMQ
Connection.default_user;
String password = Activemqconnection.default_password;
String url = activemqconnection.default_broker_url;
return new activemqconnectionfactory (user, password, URL);
} public class Asynchsubscriber extends Thread {Private class TextListener implements MessageListener {
Final Sampleutilities.donelatch monitor = new Sampleutilities.donelatch (); If you receive a message onThe message is invoked (implements the MessageListener proxy) public void OnMessage {if message Instan
Ceof textmessage) {textmessage msg = (textmessage) message;
try {System.out.println ("Subscriber thread: Read message:" + msg.gettext ());
catch (JMSException e) {System.out.println ("Exception in OnMessage ():" + e.tostring ());
} else {//received a textmessage type of message, Publisher instructs you to end the subscription
Monitor.alldone ();
}}//end TextListener class definition/** * runs the thread.
*/public void run () {connectionfactory topicconnectionfactory = null;
Connection topicconnection = null;
Session topicsession = NULL;
Topic Topic = null; MessageConsumer topicsubscriber = null;
TextListener topiclistener = null;
try {topicconnectionfactory = Asynchtopicexample.getjmsconnectionfactory ();
Topicconnection = Topicconnectionfactory.createconnection ();
Topicsession = Topicconnection.createsession (false, Session.auto_acknowledge);
TOPIC = Topicsession.createtopic (topicname);
catch (Exception e) {System.out.println ("Connection problem:" + e.tostring ());
if (topicconnection!= null) {try {topicconnection.close ();
The catch (jmsexception ee) {}} system.exit (1);
try {topicsubscriber = Topicsession.createconsumer (topic);
Topiclistener = new TextListener ();
Topicsubscriber.setmessagelistener (Topiclistener); Topicconnection.start ();
* * asynchronously process messages.
* Block until Publisher issues a control message indicating * end of publish stream.
* * TopicListener.monitor.waitTillDone ();
catch (JMSException e) {System.out.println ("Exception occurred:" + e.tostring ());
Exitresult = 1; finally {if (topicconnection!= null) {try {Topicconnecti
On.close ();
catch (JMSException e) {exitresult = 1; {}}}}/** * The Multiplepublisher class publishes several Messa
GE to a topic.
* * @author Kim Haase * @version 1.6, 08/18/00/public class Multiplepublisher extends Thread {
/** * Runs the thread.
*/public void run () {connectionfactory topicconnectionfactory = null;
Connection topicconnection = null;
Session topicsession = NULL;
Topic Topic = null;
MessageProducer topicpublisher = null;
TextMessage message = NULL;
Final int nummsgs = 20;
Final String msg_text = new String ("Here was a message");
try {topicconnectionfactory = Asynchtopicexample.getjmsconnectionfactory ();
Topicconnection = Topicconnectionfactory.createconnection ();
Topicsession = Topicconnection.createsession (False,session.auto_acknowledge);
TOPIC = Topicsession.createtopic (topicname);
catch (Exception e) {System.out.println ("Connection problem:" + e.tostring ());
if (topicconnection!= null) { try {topicconnection.close ();
The catch (jmsexception ee) {}} system.exit (1);
try {topicpublisher = topicsession.createproducer (topic);
message = Topicsession.createtextmessage ();
for (int i = 0; i < nummsgs i++) {message.settext (Msg_text + "" + (i + 1));
System.out.println ("Publisher: Post message:" + message.gettext ());
Topicpublisher.send (message);
//Send a Non-text control message indicating end of messages.
Topicpublisher.send (Topicsession.createmessage ());
catch (JMSException e) {System.out.println ("Exception occurred:" + e.tostring ());
Exitresult = 1;
finally {if (topicconnection!= null) {try { Topicconnection.close ();
catch (JMSException e) {exitresult = 1; "}}}} public void Run_threads () {Asynchsubscriber ASYNCHSU
Bscriber = new Asynchsubscriber ();
Multiplepublisher multiplepublisher = new Multiplepublisher ();
Multiplepublisher.start ();
Asynchsubscriber.start ();
try {asynchsubscriber.join ();
Multiplepublisher.join (); catch (Interruptedexception e) {}} public static void Main (string[] args) {Asynchtopicexample ate =
New Asynchtopicexample ();
Ate.topicname = "Myfirsttopic";
System.out.println ("Topic name is" + ate.topicname);
Ate.run_threads ();
}
}
reference materials
[1] "Getting Started in Active MQ (Turn)"
http://yeweiyun868.blog.163.com/blog/static/563784432010112301916556/
[2] How to add src and Javadoc in eclipse
Http://hi.baidu.com/rebeccacao/blog/item/d3f67ed3af8384229b5027bf.html
[3] Active MQ Official website
http://activemq.apache.org/
[4] Java message Service specification contains JMS1.1 standard sample code
Http://www.oracle.com/technetwork/java/docs-136352.html
[5] "JMS Example:publish and Subscribe"
Http://jmsexample.zcage.com/index2.html