1, through the previous section "", we have a certain understanding of Message Queuing and JMS, but like the first section of writing asynchronous message communication is more troublesome, through the integration with spring, we can be very simple to use.
This example is built with Maven, and the code is as follows:
The pom file is as follows: The main use of the jar package is spring-related, JUnit-related, MQ-related
<!--Spring--<dependency> <groupId>org.springframework</groupId> <artifa
Ctid>spring-webmvc</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-jdbc<
;/artifactid> <version>${spring.version}</version> </dependency> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupid> ;org.springframework</groupid> <artifactId>spring-test</artifactId> <VERSION>${SPR Ing.version}</version> <scope>provided</scope> </dependency> <!--activemq--&G
T <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-spring</artifactId> &L T;version>${activemq.version}</version> </dependency> <!--spring-jms--<dependency&
Gt <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <ver Sion>${spring.version}</version> </dependency> <!--log--<dependency> < ;groupid>org.slf4j</groupid> <artifactId>slf4j-log4j12</artifactId> <version>${ Slf4j.version}</version> </dependency> <!--unit Test--<dependency> <groupid& Gt;junit</groupid> <artifactId>junit</artifactId> <version>${junit.version}</ve Rsion> <scope>test</scope> </dependency>
The
ACTIVEMQ related configuration file is as follows:
Applicationcontext-activemq.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jee= "Http://www.springframework.org/schema/jee" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:amq=" Http://activemq.apache.org/schema/core "xmlns:jms=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/jee/http Www.springframework.org/schema/jee/spring-jee.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-3.0.xsd Http://www.springframework.org/schema/context http:Www.springframework.org/schema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS/HTTP Www.springframework.org/schema/jms/spring-jms-4.0.xsd Http://activemq.apache.org/schema/core/HTTP Activemq.apache.org/schema/core/activemq-core-5.8.0.xsd "default-lazy-init=" false "> <!--activemq Connection factory--&G
T <!--can actually generate connection connectionfactory, provided by the corresponding JMS service provider-<!--if the network is connected: tcp://ip:61616; network not connected: tcp:// localhost:61616 and Username, password---<amq:connectionfactory id= "amqconnectionfactory" Brokerurl= "${activemq.url}" t Rustallpackages= "true" Username= "${activemq.username}" password= "${activemq.password}"/> <!--Spring Caching Connect Factory-<!--spring to manage real connectionfactory connectionfactory---<bean id= "ConnectionFactory" class= " Org.springframework.jms.connection.CachingConnectionFactory "> <!--target connectionfactory corresponds to the real can generate JMS Connecti On ConnectionFactory--<property name= "tarGetconnectionfactory "ref=" Amqconnectionfactory "></property> <!--session cache count-<prope Rty name= "sessioncachesize" value= "${activemq.sessioncachesize}" ></property> </bean> <!--Sprin G Jmstemplate message producer Start--> <!--definition jmstemplate queue type--<bean id= "queuetemplate" class= "Org.sprin
Gframework.jms.core.JmsTemplate "> <!--this connectionfactory corresponds to the ConnectionFactory object that we have defined spring provides-- <constructor-arg ref= "ConnectionFactory"/> <!--non-pub/sub model (publish/subscribe), that is, queue mode--<proper Ty name= "Pubsubdomain" value= "false"/> </bean> <!--Spring jmstemplate message producer End--> </beans> ;
The producers are as follows:
/**
* MQ producer
* @author Administrator
* */
@Service public
class Studentproducerservice {
Public final static Logger Logger = Loggerfactory.getlogger (studentproducerservice.class);
/**
* Queue name
*
/@Value ("${test.queue}")
private String queuename;
@Autowired
private jmstemplate queuetemplate;
/**
* Send messages to the MQ queue */
public
void SendMessage (final Student Student) {
queuetemplate.send ( QueueName, New Messagecreator () {
@Override public
Message CreateMessage (Session session) throws jmsexception {
ObjectMessage message = Session.createobjectmessage ();
Logger.debug ("producer will send message:" Producer "" +student.tostring ());
Message.setobject (student);
return message;}}
);
}
Consumers:
/**
* MQ Consumer
* @author Administrator
* */
@Service public
class Studentconsumerservice {
Public final static Logger Logger = Loggerfactory.getlogger (studentconsumerservice.class);
/**
* Queue name
*
/@Value ("${test.queue}")
private String queuename;
@Autowired
private jmstemplate queuetemplate;
/**
* Receive message */public
void Receivermessage () {
Message message = (message) queuetemplate.receive ( QueueName);
ObjectMessage objmessage = (objectmessage) message;
try {
Object obj = Objmessage.getobject ();
if (obj instanceof Student) {
logger.debug ("Server received message: +" receiver "" +obj.tostring ()) "
}
} catch ( JMSException e) {
e.printstacktrace ();}}
}
The test run code is as follows:
@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ({"Classpath:spring/applicationcontext*.xml"} ) Public
class Studentproducerservicetest {
@Autowired
private Studentproducerservice Studentproducerservice;
@Autowired
private Studentconsumerservice studentconsumerservice;
@Test public
void Testsendmessage () {
final Student Student = new Student ("201712291122", "Onionflower", 12, 2); C9/>system.out.println ("Ready to start running the producer ....") ");
Studentproducerservice.sendmessage (student);
System.out.println ("Ready to start running the consumer ....") ");
Studentconsumerservice.receivermessage ();
}
}
Operation Result:
From the test results above we can see that the producer produces a message that the consumer consumes a message, but we will find that the use case has problems:
1, consumers need to run manually, do not listen to the queue at any time "if found that there is a message, automatic consumption."
2, the code is not optimized.
The optimized code is as follows:
Configuration file Increase:
Applicationcontext-activemq.xml
<bean id= "QueueReceiver" class= "Com.onion.mq.optimize.OptimizeConsumerService" ></bean>
< !--define the queue listener--
<jms:listener-container destination-type= "queue" container-type= "default" receive-timeout= "connection-factory=" ConnectionFactory "acknowledge=" Auto ">
<jms:listener destination= "${test.queue}" ref= "QueueReceiver"/>
</jms:listener-container>
Producers:
/** *
after optimized producer
* @author Administrator * */
@Service public
class optimizeproducerservice{ Public
final static Logger Logger = Loggerfactory.getlogger (optimizeproducerservice.class);
/**
* Queue name
*
/@Value ("${test.queue}")
private String queuename;
/**
* Jmstemplete Packaging, the method of sending messages Unified packaging */
@Autowired
private mqservice mqservice;
/**
* Send message to MQ queue */public
void SendMessage (Student Student) {
Logger.debug ("producer will send message:" Producer "" +student.tostring ());
Studentmessagecreator studentcreator = new Studentmessagecreator (student);
Mqservice.queuesend (QueueName, studentcreator);
}
}
Package Jmstemplete
/**
* @author onionflower
* @date July 12, 2017 * *
@Service public
class Mqservice {
@Autowired ( Required=false)
private jmstemplate queuetemplate;
public void Queuesend (String queuename,messagecreator messagecreator) {
queuetemplate.send (queuename, messagecreator);
}
}
Extract the Messagecreator.
/**
* Optimize the generated code, we extract the new Messagecreator from the producer, generate a separate class
* @author Administrator
* *
/Public Class Studentmessagecreator implements messagecreator{
private Student Student;
Public Studentmessagecreator (Student Student) {
super ();
This.student = student;
}
@Override public
Message CreateMessage (Session session) throws JMSException {
ObjectMessage message = Session.createobjectmessage ();
Message.setobject (student);
return message;
}
}
Consumers:
/**
* MQ Consumer
* @author Administrator * */Public
class Optimizeconsumerservice implements messagelistener{public
final static Logger Logger = Loggerfactory.getlogger (optimizeconsumerservice.class);
@Override public
void onMessage (Message message) {
ObjectMessage objmessage = (objectmessage) Message;
Object obj = null;
try {
obj = Objmessage.getobject ();
if (obj instanceof Student) {
logger.debug ("Server received message: +" receiver "" +obj.tostring ()) "
}
} catch ( JMSException e) {
e.printstacktrace ();}}
}
The results of the operation are as follows:
We only need to run the producer, the consumer will automatically listen to the queue for non-consumption of messages, if any, directly take past consumption.
Second, activemq cluster configuration
ACTIVEMQ cluster, we only need to modify the spring configuration file: Modify the associated configuration of the connection factory. The specific code is as follows:
<amq:connectionfactory id= "Amqconnectionfactory" Brokerurl= "${activemq.url}"
trustallpackages= "true" Username= "${activemq.username}" password= "${activemq.password}"/>
About the properties configuration file is as follows:
Activemq.url=failover: (tcp://xxxx:61616,tcp://xxxxx:61616,tcp://xxxxx:61616)?initialreconnectdelay=0& maxreconnectattempts=3&timeout=2000
Activemq.username=admin
Activemq.password=admin
activemq.sessioncachesize=100
The source code download address is as follows: http://download.csdn.net/download/u012151597/10179978