Spring consolidates JMS

Source: Internet
Author: User
Tags gettext

Spring consolidates instances of JMS (message middleware)

This article mainly describes how to configure SPRING-JMS, as to why this configuration and SPRING-JMS related, please read this article: Spring Integrated JMS (message middleware). Our message broker here is using ACTIVEMQ.

First, the relevant configuration

This article explains how to configure JMS in spring, and the configuration of spring itself does not introduce much.

1.1 Configuring MAVEN Dependencies

Configure dependent dependencies before using SPRING-JMS.

<!--Java JMS native API--><dependency> <groupId >javax.jms</groupId> <artifactId>javax.jms-api</artifactId> <version>2.0</version ></dependency><!--spring-jms API--><dependency> <groupid>org.springframework</ Groupid> <artifactId>spring-jms</artifactId> <version>${spring.version}</version><   /dependency><!--active-mq Core Pack--><dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> <version>5.7.0</version></dependency><! --Spring-test class for testing--><dependency> <groupId>org.springframework</groupId> <artifactId> Spring-test</artifactid> <version>${spring.version}</version></dependency>  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
1.2 Installing and starting ACTIVEMQ

Here is a brief description of how to install the boot activemq, please refer to the official documentation for details.

    1. Download activemq:http://activemq.apache.org/download.html
    2. Installation:
      -Unzip: Tar zxvf activemq-x.x.x-bin.tar.gz
      -Add Permissions:
      cd [activemq_install_dir]/bin
      chmod 755 activemq

    3. Start:
      cd [activemq_install_dir]/bin
      ./activemq start

    4. Check whether the startup was successful:
      netstat -nl|grep 61616

We can also view the ACTIVEMQ operation through the monitoring page: http://localhost:8161/admin (default username password is Admin)

1.3 Configuring JMS-related Beans
<?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:jms= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS" xmlns:amq=                       "Http://activemq.apache.org/schema/core" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/s                       Chema/context http://www.springframework.org/schema/context/spring-context.xsd                       HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS http://www.springframework.org/schema/jms/spring-jms.xsd Http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/ Activemq-core.xsd "><!--configure C for connection ActivemqOnnectionfactory--><bean id= "amqconnectionfactory" class= "Org.apache.activemq.ActiveMQConnectionFactory" P:brokerurl= "tcp://localhost:61616"/><!--to improve efficiency, configure a connection pool--><bean id= "Cachedconnectionfactory" class= " Org.springframework.jms.connection.CachingConnectionFactory "p:targetconnectionfactory-ref=" Amqconnectionfactory "p:sessioncachesize="/><!--configuration broker Destination--><bean id= "Destination" cl ass= "Org.apache.activemq.command.ActiveMQQueue" > <constructor-arg value= "FOO. TEST "/></bean><!--Configure Spring jmstemplate--><bean id=" producertemplate "class=" Org.springframework.jms.core.JmsTemplate "p:connectionfactory-ref=" Cachedconnectionfactory "p:defaultdestination -ref= "Destination"/></beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

As you can see from this configuration, the configuration here is more than the one described in the spring Consolidated JMS (message middleware) article cachedConnectionFactory . We know that creating and destroying connections is very resource-intensive, and in order to solve the resource consumption associated with creating a destroy connection, we typically introduce a connection pool or cache. Normal jmstemplate connectionfactory need to establish a new connection each time the message is sent, so the efficiency is very low, so in the specific configuration, we want to use the connection pool or cache, so the configuration here is added as a cachedConnectionFactory cache.

Second, send a message

Write a jmsmessageproducer asynchronous send message:

 @Componentpublic class Jmsmessageproducer {private static    Final Logger Logger = Loggerfactory.getlogger (Jmsmessageproducer.class);    @Autowired protected jmstemplate jmstemplate;    protected int numberofmessages = 10;        public void Sendmessages () throws jmsexception {StringBuilder payload = null;            for (int i = 0; i < numberofmessages; ++i) {payload = new StringBuilder ();            Payload.append ("Message ["). Append (i). Append ("] sent at:"). Append (New Date ());            Jmstemplate.convertandsend (Payload.tostring ());        Logger.info ("Sending message number [" + i + "]"); }    }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
Iii. Receiving Messages 3.1 Way One: Write a Jmsmessageconsumer to receive messages synchronously
@Componentpublic class JmsMessageConsumer {    private static final Logger logger = LoggerFactory.getLogger(JmsMessageProducer.class);    @Autowired    private JmsTemplate template;    public void receiveMessages() throws JMSException {        Message message =template.receive();        TextMessage textMessage =(TextMessage)template.receive();        logger.info(textMessage.getText());    }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
3.2 Mode two: Write a Jmsmessagelistener listener to receive messages asynchronously
@Componentpublic class JmsMessageListener implements MessageListener{    private static final Logger logger = LoggerFactory.getLogger(JmsMessageListener.class);    public void onMessage(Message message) {        try {            TextMessage msg = (TextMessage) message;            logger.info("Consumed message: " + msg.getText());        } catch (JMSException e) {            e.printStackTrace();        }    }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

You will also need to configure this listener in the configuration file after you finish writing listener:

<!-- 注入我们写的listener --><bean id="jmsMessageListener" class="com.heaven.spring.jms.JmsMessageListener"/><!-- 配置listener到listener-container当中 --><jms:listener-container        container-type="default"        connection-factory="cachedConnectionFactory"        acknowledge="auto">    <jms:listener destination="FOO.TEST" ref="jmsMessageListener" method="onMessage"/></jms:listener-container>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
Four, test it. 4.1 Test Send Asynchronous message

Write a jmsmessageproducertest test to send:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:spring/root-context.xml")public class JmsMessageProducerTest {    @Autowired    JmsMessageProducer jmsMessageProducer;    @Test    public void testSend(){        try {            jmsMessageProducer.sendMessages();        } catch (JMSException e) {            e.printStackTrace();        }    }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

Look at the results of the operation:

The message has been sent asynchronously, and although there is no consumer consumption, the message is treated as if it had been successfully processed.

4.2 Testing Synchronous receive messages

Write a jmsmessageconsumertest test to receive:

 @RunWith (springjunit4classrunner.class) @ Contextconfiguration (locations = "Classpath:spring/root-context.xml") public class Jmsmessageconsumertest {@    Autowired Jmsmessageconsumer Jmsmessageconsumer;        @Test public void Testsend () {try {jmsmessageconsumer.receivemessages ();        } catch (JMSException e) {e.printstacktrace (); }    }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

Look at the results of the operation:

We can see that the consumer receives a message, the first message sent by the sender above. If we run it again, we will receive a second message. If all the messages are consumed and there is no message in the broker, the Jmsmessageconsumertest process will hang until a new message is generated, and you can try it.

4.3 Test the asynchronous message reception

Follow the 3.2 sections above to write a description JmsMessageListener and configure it listener-container in. JmsMessageListenerthis will listen to brokerURL="tcp://192.168.134.128:61616" the port in real time, and once a message is generated, the message will be received in the onMessage() method. In fact at this time our producer and listeners are in the same application, if we run producer again, we can see the following results:

By running the results, you can see that whenever a producer produces a message, the listener receives the message in real time.

Spring consolidates JMS

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.