Integration of ACTIVEMQ Spring

Source: Internet
Author: User
Tags aop

ACTIVEMQ can be easily integrated with spring, Spring provides a series of interface classes, very useful!

such as asynchronous message data, asynchronous send mail, asynchronous message query, etc.

<dependency><groupid>org.apache.activemq</groupid><artifactid>activemq-all</ Artifactid><version>5.11.1</version></dependency><dependency><groupid> org.apache.activemq</groupid><artifactid>activemq-pool</artifactid><version>5.11.1< /version></dependency><dependency><groupid>org.springframework</groupid>< Artifactid>spring-jms</artifactid><version>${spring.version}</version></dependency>

  

The first two ACTIVEMQ jar packages are introduced,

The

is then spring-activemq for configuration:

<?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:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:              Www.springframework.org/schema/beans/spring-beans-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP             Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX Http://www.springframework.org/schema/tx/spring-tx-3.2.xsd Http://www.springframework.org/schema/cont Ext http://www.springframework.org/schema/context/spring-context-3.2.xsd "default-autowire=" ByName "Default-laz Y-init= "false" ><!--third-party MQ factory: ConnectionFactory--&GT;<bean id= "Targetconnectionfactory" class= "org.apache.activemq.ActiveMQConnectionFactory" ><!--activemq Address--<property name= "Brokerurl" value= "${activemq.brokerurl}"/> <property name= "UserName "Value=" ${activemq.username} "></property> <property name=" password "value=" ${activemq.password} ">&    Lt;/property> </bean> <!--ACTIVEMQ gives us a pooledconnectionfactory by injecting a activemqconnectionfactory into it Can be used to connection, session and MessageProducer pooling, which can greatly reduce our resource consumption, to rely on the Activemq-pool package--><bean id= " Pooledconnectionfactory "class=" org.apache.activemq.pool.PooledConnectionFactory "><property name=" ConnectionFactory "ref=" targetconnectionfactory "/><property name=" MaxConnections "value=" ${ Activemq.pool.maxConnections} "/></bean><!--spring for managing real connectionfactory connectionfactory-- <bean id= "ConnectionFactory" class= "Org.springframework.jms.connection.SingleConnectionFactory" ><! --the target connectionfactory corresponds to the real connectionfactory--><property name= "targetconnectionfactory" that can generate the JMS connection ref= "Pooledconnectionfactory"/></bean><!--the JMS tool class provided by spring, which can be used for message sending, receiving, etc.--><!--queue templates-->< Bean id= "jmstemplate" class= "Org.springframework.jms.core.JmsTemplate" > <!-- This connectionfactory corresponds to the ConnectionFactory object that we have defined spring provides--<property name= "ConnectionFactory" ref= " ConnectionFactory "/> <property name=" defaultdestinationname "value=" ${activemq.queuename} "></property ></bean> </beans>

Create a third-party MQ factory: ConnectionFactory

Then create the producer Mqproducer:

Package Bhz.mq;import Javax.jms.jmsexception;import Javax.jms.message;import javax.jms.session;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.jms.core.jmstemplate;import Org.springframework.jms.core.messagecreator;import Org.springframework.stereotype.service;import Bhz.entity.Mail ; Import com.alibaba.fastjson.jsonobject;/** * <B> system name:</b><br> * <B> Module Name: </b><br > * <B> Chinese class name:</b><br> * <B> Description:</b><br> * @author jxh */@Service ("Mqproducer") public class Mqproducer {private Jmstemplate jmstemplate;public jmstemplate getjmstemplate () {return jmstemplate;} @Autowiredpublic void Setjmstemplate (Jmstemplate jmstemplate) {this.jmstemplate = jmstemplate;} /** * <B> method name:</b> send mail Message object <BR> * <B> description:</b> Send Message object <BR> * @param mail */public void SendMessage (final mail mail) {jmstemplate.send (new Messagecreator () {public Message CreateMessage (session session)Throws JMSException {return session.createtextmessage (jsonobject.tojsonstring (mail));}});}} 

Look at the Mail entity class:

Package Bhz.entity;public class Mail {/** sender **/private string from;/** recipient **/private String to;/** topic **/private string subject;/** message content **/private string Content;public Mail () {}public mail (string from, string to, string subject, String cont ENT) {super (); this.from = from;this.to = To;this.subject = Subject;this.content = content;} Public String Getfrom () {return from;} public void Setfrom (String from) {this.from = from;} Public String Getto () {return to;} public void Setto (String to) {this.to = to;} Public String Getsubject () {return subject;} public void Setsubject (String subject) {this.subject = subject;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;}}

The following message is sent, and the test is sent through JUnit:

Package Bhz.test;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Bhz.entity.mail;import Bhz.mq.MQProducer ;/** * <B> system name:</b><br> * <B> Module name:</b><br> * <B> Chinese class name:</b><br> * <B> Description:</b><br> * @author jxh */@ContextConfiguration (locations = {"Classpath:spring-context.xml") }) @RunWith (springjunit4classrunner.class) public class Testproducer {@Autowiredprivate mqproducer mqproducer;@ testpublic void Send () {Mail mail = new mail (); Mail.setto ("[email protected]"); Mail.setsubject ("Asynchronously sent Mail"); Mail.setcontent ("Hi,this is a message!"); This.mqProducer.sendMessage (mail); SYSTEM.OUT.PRINTLN ("Send succeeded..");}}

Here's a look at the configuration of the consumer's project Activemq-consumer:

One more config for this project

# # ActiveMQ Configurationactivemq.brokerurl=tcp\://192.168.1.200\:61616activemq.username=bhzactivemq.password= bhzactivemq.pool.maxconnections=10#queuenameactivemq.queuename=mailqueue## SMTP configurationmail.host= smtp.163.com# #mail. port=21mail.username=***@163.commail.password=mail.smtp.auth=truemail.smtp.timeout= 30000mail.default.from=***@163.com

Look at the consumer of the consumer's Spring-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:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:              Www.springframework.org/schema/beans/spring-beans-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP             Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX Http://www.springframework.org/schema/tx/spring-tx-3.2.xsd Http://www.springframework.org/schema/cont Ext http://www.springframework.org/schema/context/spring-context-3.2.xsd "default-autowire=" ByName "Default-laz Y-init= "false" ><!--third-party MQ factory: ConnectionFactory--&GT;<bean id= "Targetconnectionfactory" class= "Org.apache.activemq.ActiveMQConnectionFactory" ><!-- ACTIVEMQ Service Address--<property name= "Brokerurl" value= "${activemq.brokerurl}"/> <property name= "use Rname "value=" ${activemq.username} "></property> <property name=" password "value=" ${activemq.password} " ></property> </bean> <!--ACTIVEMQ provides us with a pooledconnectionfactory, By injecting a activemqconnectionfactory into it can be used to pool connection, session and MessageProducer, which can greatly reduce our resource consumption and depend on Activemq-pool bag--><bean id= "pooledconnectionfactory" class= " Org.apache.activemq.pool.PooledConnectionFactory "><property name=" ConnectionFactory "ref=" Targetconnectionfactory "/><property name=" MaxConnections "value=" ${activemq.pool.maxconnections} "/>< /bean><!--Spring is used to manage the real connectionfactory connectionfactory--><bean id= "ConnectionFactory" class= " Org.springframework.jms.connection.SingleConnectionFactory "><!--the target connectionfactory corresponds to the real connectionfactory--><property name= "targetconnectionfactory" that can generate the JMS connection ref= "Pooledconnectionfactory"/></bean><!--the JMS tool class provided by spring, which can be used for message sending, receiving, etc.--><!--queue templates-->< Bean id= "jmstemplate" class= "Org.springframework.jms.core.JmsTemplate" > <!-- This connectionfactory corresponds to the ConnectionFactory object that we have defined spring provides--<property name= "ConnectionFactory" ref= " ConnectionFactory "/> <property name=" defaultdestinationname "value=" ${activemq.queuename} "></property ></bean> <!--This is the destination: MailQueue--><bean id= "MailQueue" class= " Org.apache.activemq.command.ActiveMQQueue "><constructor-arg><value>${activemq.queuename}</ value></constructor-arg></bean><!--Configuring Custom listening: MessageListener--><bean id= " Mailqueuemessagelistener "class=" Bhz.mq.MailQueueMessageListener "></bean><!--will connect the factory, target, Custom Listener Injection JMS template--><bean id= "Sessionawarelistenercontainer" CLAss= "Org.springframework.jms.listener.DefaultMessageListenerContainer" ><property name= "ConnectionFactory" ref= "ConnectionFactory"/><property name= "Destination" ref= "MailQueue"/><property name= " MessageListener "ref=" Mailqueuemessagelistener "/></bean></beans>

Because you want to send a message, there is also a configuration for the message:

<?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:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:cache=" Http://www.springframework.org/schema/cache "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-3.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.2.xsd Http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/ Spring-cache-3.2.xsd > <!--Spring provides a high-level abstraction class for sending e-mail--><bean id= "MailSender" class= "Org.springframework.mail.javamail.Ja Vamailsenderimpl "><property name=" host "value=" ${mail.host} "/><property name=" username "value=" ${ Mail.username} "/><property name=" password "value=" ${mail.password} "/><property name=" defaultEncoding " Value= "UTF-8" ></property><property name= "javamailproperties" ><props><prop key= " Mail.smtp.auth ">${mail.smtp.auth}</prop><prop key=" Mail.smtp.timeout ">${mail.smtp.timeout}</ Prop></props></property></bean><bean id= "Simplemailmessage" class= " Org.springframework.mail.SimpleMailMessage "><property name=" from "><value>${mail.default.from} </value></property></bean><!--Configuring the thread pool--><bean id= "ThreadPool" class= " Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor "><!--thread pool maintains a minimum number of threads--><property name = "Corepoolsize" value= "5"/><! --The thread pool maintains the idle time allowed by threads--><property name= "Keepaliveseconds" value= "30000"/><!--thread pool maintains the maximum number of threads-->< Property Name= "Maxpoolsize" value= "/><" buffer queue used by!--thread pool--><property name= "queuecapacity" value= "100"/ ></bean></beans>

The Mail entity class is the same as before,

Look at the listener that receives the message,

Package Bhz.mq;import Javax.jms.destination;import Javax.jms.message;import javax.jms.session;import Javax.jms.textmessage;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.jms.core.jmstemplate;import Org.springframework.jms.listener.SessionAwareMessageListener; Import Org.springframework.stereotype.component;import Bhz.entity.mail;import Bhz.service.mailservice;import com.alibaba.fastjson.jsonobject;/** * <B> system name:</b><br> * <B> Module name:</b><br> * < B> Chinese class name:</b><br> * <B> Description:</b><br> * @author JXH */@Componentpublic class Mailqueuemessagelistener implements sessionawaremessagelistener<message> {@Autowiredprivate jmstemplate Jmstemplate, @Autowiredprivate Destination mailqueue; @Autowiredprivate mailservice mailservice;public synchronized void onMessage (Message message, session session) {try {textmessage msg = (textmessage) message;final String ms = Msg.gette XT (); System.out.println ("received message:" + ms);//converted to the corresponding object mail mail = Jsonobject.parseobject (MS, Mail.class); if (mail = = null) {return;} try {//Execute Send Business mailservice.mailsend (mail),} catch (Exception e) {//Send exception, re-put back to queue//jmstemplate.send (MailQueue, new Messagecreator () {//@Override//public Message CreateMessage (Session session) throws JMSException {//return Session.createtextmessage (MS);//}//}); E.printstacktrace ();}} catch (Exception e) {e.printstacktrace ();}}}

The

Finally calls the service that sent the message to send the message:

Package Bhz.service;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.mail.mailexception;import Org.springframework.mail.simplemailmessage;import Org.springframework.mail.javamail.javamailsender;import Org.springframework.scheduling.concurrent.threadpooltaskexecutor;import Org.springframework.stereotype.Service; Import Bhz.entity.Mail; @Service ("Mailservice") public class Mailservice {@Autowiredprivate javamailsender mailsender; @Autowiredprivate simplemailmessage simplemailmessage, @Autowiredprivate threadpooltaskexecutor threadpool;/** * < B> method name:</b> Send mail <BR> * <B> description:</b> Send mail <BR> * @param mail */public void MailSend (final Mail mail) {threadpool.execute (new Runnable () {public void run () {try {simplemailmessage.setfrom ( Simplemailmessage.getfrom ()); Simplemailmessage.setto (Mail.getto ()); Simplemailmessage.setsubject (Mail.getsubject ()); Simplemailmessage.settext (Mail.getcontent ()); MailSender.send ( Simplemailmessage);} CAtch (mailexception e) {e.printstacktrace (); throw e;}});}} 

Mail configuration means that when you are done, you can send the message normally, which is to send the message asynchronously via ACTIVEMQ.

  

 

Integration of ACTIVEMQ Spring

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.