ActiveMQ is a high-performance messaging middleware, primarily for JMS implementations, while other languages can be used as well. Its support point to point, publish/subscribe, push-pull mode, specific reader network, here slightly.
1, the first download ACTIVEMQ, and successfully started the service.
2, build Maven project, add dependencies
Activemq-all-5.6.0.jar
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms< /artifactid>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
3, Jms.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" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframe WORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "default-autowire=" ByName "Defau Lt-lazy-init= "false" > <!--connection factory--> <bean id= "ConnectionFactory" Org.apache.activemq.ActiveMQConnectionFactory "> <property name=" brokerurl "value=" tcp://127.0.0.1:61616? Jms.useasyncsend=true "/> <!--jms.useasyncsend=true Specifies the asynchronous mode, performance is 5 times times higher than the synchronous mode--> </bean> <!--Message Queuing (destination)--> <bean id= "Demoqueue" class= "Org.apache.activemq.command.ActiveMQQueue" > <con Structor-arg value= "Demo"/> </bean> </beans>
4. Write simple Java classes that send messages and receive messages
public class Jmsmq {private Jmstemplate jmstemplate;
Private Queue Demoqueue; public void Setconnectionfactory (ConnectionFactory connectionfactory) {this.jmstemplate = new Jmstemplate (
ConnectionFactory); This.jmsTemplate.setDeliveryMode (deliverymode.non_persistent);//Message not persisted// This.jmsTemplate.setDeliveryPersistent (false);//Message not persisted} public void Setdemoqueue (Queue demoqueue) {This.demoqueue
= Demoqueue; ///Send Message public void Simplesend (final Long size) {this.jmsTemplate.send (This.demoqueue, New Messagecreator () {PU
Blic message CreateMessage throws jmsexception {objectmessage msg = Session.createobjectmessage ();
Msg.setobject (size);
return msg;
}
});
///Receive messages public void Simplereceive () {message = Jmstemplate.receive (Demoqueue);
if (message instanceof objectmessage) {objectmessage msg = (objectmessage) message;
Long size;
try {size = (Long) msg.getobject (); System.out.println ("OnMessage ["+ size +"]);
catch (JMSException e) {e.printstacktrace ();
} else {throw new IllegalArgumentException ("Message must is of type ObjectMessage."); }
}
}
5, Jmsexample.xml
<bean id= "jmsmq" class= "Jmsexample". Jmsmq "/>
5. Write Test class
public class Jmsmqtest {public
static void Main (string[] args) {
ApplicationContext ctx = new Classpathxmlapplica Tioncontext ("Jms.xml", "Jmsexample.xml");
JMSMQ MQ = (JMSMQ) ctx.getbean ("jmsmq");
Long start = System.currenttimemillis ();
for (long i=0;i<1000;i++) {
mq.simplesend (i);//Send message, 7000 milliseconds 1000 times in asynchronous mode.
}
SYSTEM.OUT.PRINTLN ("Time Consuming:" + (System.currenttimemillis ()-start));
// Long Start1 = System.currenttimemillis ();
For (long i=0;i<10000;i++) {
// mq.simplereceive ();//Get message
// }
// SYSTEM.OUT.PRINTLN ("Time Consuming:" + (System.currenttimemillis ()-Start1));
}
The JMS development process has been completed, and the test class includes sending messages and receiving messages. But receiving messages is active, which is called "pull" mode.
Here is an example of listening to a message on a specified queue, which is "push" mode:
1, write listening to the Java class message, you need to implement the interface
public class Examplelistener implements MessageListener {public
void OnMessage (message) {
if Stanceof objectmessage) {
objectmessage msg = (objectmessage) message;
Long size;
try {
size = (Long) msg.getobject ();
System.out.println ("onMessage [" + Size + "]");
} catch (JMSException e) {
e.printstacktrace ();
}
} else {
throw new IllegalArgumentException (
" Message must is of type ObjectMessage. ");}}
2, Jmsexample-listener.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" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframe WORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "default-autowire=" ByName "Defau Lt-lazy-init= "false" > <!--this are the message driven POJO (MDP)--> <bean id= "Examplelistener" class= "Jmse" Xample. Examplelistener "/> <!--and this are the message listener container--> <bean" id= "Jmscontainer" org. Springframework.jms.listener.DefaultMessageLiStenercontainer "> <property name=" connectionfactory "ref=" ConnectionFactory "/> <property-name=" Destination "ref=" Demoqueue "/> <property name=" MessageListener "ref=" Examplelistener "/> </bean> < /beans>
3, Start message monitoring
/**
* Monitor Message Queuing
*
/public class Listenertest {public
static void Main (string[] args) {
new classpathx Mlapplicationcontext ("Jms.xml", "Jmsexample-listener.xml");
}
We've already talked about push-pull mode, sending messages and receiving messages.
In addition, spring wraps the JMS and can encapsulate remote method calls (RPC) into JMS, and see the procedure for JMS implementing a message method invocation.
emphasis: MQ can not only relieve system pressure, but also let the system decouple from the system. Through message delivery, you can implement the interaction between the two systems. As with the observer pattern, the degree of coupling between the interacting objects is reduced.
1, write the interface
Public interface Checkingaccountservice {public
void Cancelaccount (Long accountid);
public void Saveaccount (Long accountid);
2, write implementation class
public class Simplecheckingaccountservice implements Checkingaccountservice {public
void Cancelaccount (Long AccountId) {
double result = 0 D;
for (int i=0; i<accountid;) {Result
= 31/++i;
}
System.out.println ("Cancelling account [" + AccountId + "]" + ", result=" + result);
}
public void Saveaccount (Long accountid) {
System.out.println ("Saving account [" + AccountId +] ");
}
3, write client Client.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" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframe WORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "default-autowire=" ByName " Default-lazy-init= "false" > <bean id= "checkingaccountservice" class= " Org.springframework.jms.remoting.JmsInvokerProxyFactoryBean "><!--This is a factory, returns an interface proxy, encapsulates the method call as a message and sends it to the specified queue--> &L T;property name= "Serviceinterface" value= "Com.foo.CheckingAccountService"/> <properTy name= "connectionfactory" ref= "ConnectionFactory"/> <property name= "queue" ref= "Demoqueue"/> </b Ean> </beans>
4, writing service end Server.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" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframe WORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "default-autowire=" ByName " Default-lazy-init= "false" > <bean id= "checkingaccountservice" class= " Org.springframework.jms.remoting.JmsInvokerServiceExporter "><!--This is an agent that converts the received message to a method call--> <property NA Me= "Serviceinterface" value= "Com.foo.CheckingAccountService"/> <property name= "Service "> <bean class=" com.foo.SimpleCheckingAccountService "/> </property> </bean
> <!--monitor the specified queue--> <bean class= "Org.springframework.jms.listener.SimpleMessageListenerContainer" > <property name= "ConnectionFactory" ref= "ConnectionFactory"/> <property name= "destination" ref= "DemoQueue" "/> <property name=" concurrentconsumers "value=" "/> <property" name= "MessageListener" ref= "Chec" Kingaccountservice "/><!--when a message is queued, the specified method is triggered to form a method call--> </bean> </beans>
5, write test class Client.java
/** uses spring JMS to invoke the server-side method *
/public class Client {public
static void Main (string[] args) throws Exception {
App Licationcontext CTX = new Classpathxmlapplicationcontext ("Jms.xml", "Client.xml");
Checkingaccountservice service = (checkingaccountservice) ctx.getbean ("Checkingaccountservice");
Service.cancelaccount (1000000000L);
System.out.println ("Invoke cancelaccount 1000000000l!");
Long Start1 = System.currenttimemillis ();
for (long i=0;i<1000;i++) {
service.saveaccount (i);
}
SYSTEM.OUT.PRINTLN ("Time Consuming:" + (System.currenttimemillis ()-Start1));
}
6, write test class Server.java
public Class Server {
//start server, listen for queues, get messages, call public
static void Main (string[] args via reflection throws Exception
{ New Classpathxmlapplicationcontext ("Jms.xml", "Server.xml");
}
Quick work, the details will not be written, anyway this thing is very simple, we see clearly.